package com.uzai.console.service.user.impl;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxpubUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.common.utils.Math;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.DesensitizeUtil;
import com.uzai.console.common.utils.EmojiUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.constant.Const;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.constant.ES.ElasticsearchUtilGroupMsg;
import com.uzai.console.dto.TbUserInfo.TbUserInfoIdDto;
import com.uzai.console.dto.TbUserInfo.TbUserInfoQuery;
import com.uzai.console.dto.TbUserInfo.TbUserInfoUpdateDto;
import com.uzai.console.dto.feign.alarm.AlarmMsgFeignDto;
import com.uzai.console.dto.feign.groupsendjob.GroupSendChildidPushDto;
import com.uzai.console.dto.feign.groupsendjob.NewGroupSendMsgDto;
import com.uzai.console.dto.feign.userextinfo.AlipayUserAuthDto;
import com.uzai.console.dto.feign.userextinfo.UserExtInfoQueryDto;
import com.uzai.console.dto.rocketmq.wechatuser.SetUserRemarkDto;
import com.uzai.console.dto.user.UserUpdateMarketingTagDto;
import com.uzai.console.dto.user.app.*;
import com.uzai.console.dto.user.useraccdetail.UserAccDetailQuery;
import com.uzai.console.dto.user.wechatuser.TimeVO;
import com.uzai.console.dto.user.wxpubuser.WxpubUserQuery;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.EsUserExtInfo;
import com.uzai.console.entity.es.WechatBlacklistPrv;
import com.uzai.console.entity.es.WechatBlacklistPub;
import com.uzai.console.entity.wxpubmanage.WxpubInfoEntity;
import com.uzai.console.enums.GroupSendJobSourceEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.CommonService;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.HistoryDataFeignService;
import com.uzai.console.service.feign.UserExtInfoFeignService;
import com.uzai.console.service.feign.UzaiBroadcastFeignService;
import com.uzai.console.service.feign.UzaiCashierServerFeignService;
import com.uzai.console.service.merchant.MerchantService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.user.AppUserService;
import com.uzai.console.service.user.AppUserTreeInfoService;
import com.uzai.console.service.user.MarketingRewardsBlackListService;
import com.uzai.console.service.user.MarketingRewardsService;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.login.LoginVo;
import com.uzai.console.vo.tbuserinfo.TbUserInfoVo;
import com.uzai.console.vo.user.MarketingRewardVo;
import com.uzai.console.vo.user.SysTagShow;
import com.uzai.console.vo.user.SysTagVo;
import com.uzai.console.vo.user.UserTreeVo;
import com.uzai.console.vo.user.app.AppUserInfoVo;
import com.uzai.console.vo.user.app.AppUserMinMaxCreateTimeVo;
import com.uzai.console.vo.user.app.AppUserPageVo;
import com.uzai.console.vo.user.app.AppUserSimpleVo;
import com.uzai.console.vo.user.useraccdetail.UserAccDetailInfoVo;
import com.uzai.console.vo.wechatprivate.wxcontacts.WxContactsInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class AppUserServiceImpl extends CommonService implements AppUserService {

    private Logger logger = LoggerFactory.getLogger(AppUserServiceImpl.class);

    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private AppUserMapper appUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private UserAccDetailMapper userAccDetailMapper;
    @Autowired
    private TbUserInfoMapper tbUserInfoMapper;
    @Autowired
    private TbTokenMapper tbTokenMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private DeviceAppInfoMapper deviceAppInfoMapper;
    @Autowired
    private UserTypeGroupMapper userTypeGroupMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private ElasticsearchUtilGroupMsg elasticsearchUtilGroupMsg;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private GroupSendJobMapper groupSendJobMapper;
    @Autowired
    private UserExtInfoFeignService userExtInfoFeignService;
    @Autowired
    private AppUserTreeInfoService appUserTreeInfoService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UzaiBroadcastFeignService uzaiBroadcastFeignService;
    @Autowired
    private ConfigPlanMapper configPlanMapper;
    @Autowired
    private WxpubUserMapper wxpubUserMapper;
    @Autowired
    private WxpubInfoMapper wxpubInfoMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private HistoryDataFeignService historyDataFeignService;
    @Autowired
    private UzaiCashierServerFeignService uzaiCashierServerFeignService;
    @Autowired
    private SysPluginMapper sysPluginMapper;
    @Autowired
    private TakeBalBlacklistMapper takeBalBlacklistMapper;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private MarketingRewardsService marketingRewardsService;
    @Autowired
    private MarketingRewardsBlackListService marketingRewardsBlackListService;
    @Autowired
    private MarketingTagMapper marketingTagMapper;

    /**
     * 分页查询微信用户列表
     *
     * @param appUserQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<AppUserPageVo> findWechatUserList(AppUserQuery appUserQuery) {

        logger.info("---查询App会员列表---appUserQuery={}", JSONObject.toJSONString(appUserQuery));

        //返回到页面分页对象
        Page<AppUserPageVo> pageVo = new Page<>();

        //新建返回到页面的LIST对象
        List<AppUserPageVo> appUserPageVoList = new ArrayList<>();

        //判断是否需要脱敏
        Boolean tuominFlag_mobile = true;
        String cmstype_user_mobile_verified =  (String)redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_USER_MOBILE, appUserQuery.getMerId()));
        if(org.apache.commons.lang3.StringUtils.isNotBlank(cmstype_user_mobile_verified)){
            tuominFlag_mobile = false;
        }

        //执行分页查询对象
        Page<AppUser> page = new Page<>();
        appUserQuery.convert(page);

        //判断是否有淘宝会员id条件
        if(org.apache.commons.lang3.StringUtils.isNotBlank(appUserQuery.getSpecialId())){
            //清空其他条件
            AppUserQuery appUserQuery_specialId = new AppUserQuery();
            appUserQuery_specialId.setMerId(appUserQuery.getMerId());
            appUserQuery_specialId.setSize(appUserQuery.getSize());
            appUserQuery_specialId.setCurrent(appUserQuery.getCurrent());
            appUserQuery_specialId.setOrder(appUserQuery.getOrder());
            appUserQuery_specialId.setAsc(appUserQuery.isAsc());
            appUserQuery_specialId.setOrderByField(appUserQuery.getOrderByField());
            appUserQuery_specialId.setOrderItemList(appUserQuery.getOrderItemList());
            appUserQuery_specialId.setSpecialId(appUserQuery.getSpecialId());
            //重新生成查询条件
            appUserQuery = appUserQuery_specialId;

            //查询淘宝会员信息
            TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
            tbUserInfoQuery.setMerId(appUserQuery.getMerId());
            tbUserInfoQuery.setSpecialId(appUserQuery.getSpecialId());
            List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(tbUserInfoQuery);
            if(tbUserInfoList != null && tbUserInfoList.size() > 0){
                List<Long> userIdList = new ArrayList<>();
                for (TbUserInfo tbUserInfo : tbUserInfoList) {
                    userIdList.add(tbUserInfo.getUserId());
                }
                appUserQuery.setIdList(userIdList);
            }else{//未查询到淘宝会员id,则返回空
                return pageVo;
            }
        }

        List<AppUser> appUserList = appUserMapper.findByList(page, appUserQuery);
        if (appUserList != null) {

            for (AppUser appUser : appUserList) {
                AppUserPageVo appUserPageVo = new AppUserPageVo();
                BeanUtils.copyProperties(appUser, appUserPageVo);

                //处理淘礼金脱敏显示
                //是否脱敏处理
                if(tuominFlag_mobile){
                    appUserPageVo.setMobile(DesensitizeUtil.around(appUserPageVo.getMobile(), 3, 4));
                }

                try {
                    //身份名称
                    appUserPageVo.setIdentityName(IdentityEnum.getById(appUserPageVo.getIdentity()).getDesc());

                    //会员类型名称
                    if (appUserPageVo.getUserType() != null) {
                        UserType userType = userTypeMapper.selectById(appUserPageVo.getUserType(), appUserQuery.getMerId());
                        if (userType != null) {
                            appUserPageVo.setUserTypeName(userType.getName());
                        }
                    }

                    //上级用户
                    if (appUserPageVo.getParentId() != null) {
                        if (appUserPageVo.getParentId() != 0) {
                            AppUser appUserParent = appUserMapper.selectById(appUserPageVo.getParentId(), appUserQuery.getMerId());
                            if (appUserParent != null) {
                                appUserPageVo.setParentName(appUserParent.getNickName());
                            }
                        } else {
                            appUserPageVo.setParentId(null);
                        }
                    }

                    //代理
                    if (appUserPageVo.getAgentId() != null) {
                        if (appUserPageVo.getAgentId() != 0) {
                            AppUser appUserAgent = appUserMapper.selectById(appUserPageVo.getAgentId(), appUserQuery.getMerId());
                            if (appUserAgent != null) {
                                appUserPageVo.setAgentName(appUserAgent.getNickName());
                            }
                        } else {
                            appUserPageVo.setAgentId(null);
                        }
                    }

                    //合伙人
                    if (appUserPageVo.getPartnerId() != null) {
                        if (appUserPageVo.getPartnerId() != 0) {
                            AppUser appUserPartner = appUserMapper.selectById(appUserPageVo.getPartnerId(), appUserQuery.getMerId());
                            if (appUserPartner != null) {
                                appUserPageVo.setPartnerName(appUserPartner.getNickName());
                            }
                        } else {
                            appUserPageVo.setPartnerId(null);
                        }
                    }

                    //查询机器人ID
                    if (appUserPageVo.getDeviceUniqueId() != null) {
                        DeviceAppInfo deviceAppInfo = deviceAppInfoMapper.selectById(appUserPageVo.getDeviceUniqueId(), appUserQuery.getMerId());
                        if (deviceAppInfo != null) {
                            appUserPageVo.setDeviceId(deviceAppInfo.getDeviceId());
                            appUserPageVo.setDeviceName(deviceAppInfo.getDeviceName());
                            appUserPageVo.setDeviceRemark(deviceAppInfo.getDeviceRemark());
                        }
                    }

                    //用户类型组信息
                    if (appUserPageVo.getUserType() != null) {
                        UserType userType = userTypeMapper.selectById(appUserPageVo.getUserType(), appUserQuery.getMerId());
                        if (userType != null) {
                            Long userTypeGroupId = userType.getGroupId();
                            if (userTypeGroupId != null) {
                                UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, appUserQuery.getMerId());
                                if (userTypeGroup != null) {
                                    appUserPageVo.setUserTypeGroupId(userTypeGroup.getId());
                                    appUserPageVo.setUserTypeGroupName(userTypeGroup.getName());
                                }
                            }
                        }
                    }

                    //标签List
                    try {
                        appUserPageVo.setTagsArr(JSONObject.parseArray(appUserPageVo.getTags(), String.class));
                    } catch (Exception e) { //如果不是JSON格式

                    }

                    //会员标签
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(appUser.getSysTags())){
                        try {
                            List<SysTagVo> userTagVoList =  JSONObject.parseArray(appUser.getSysTags(), SysTagVo.class);
                            if(userTagVoList != null && userTagVoList.size() > 0){
                                List<SysTagShow> sysTagShowList = new ArrayList<>();
                                List<Long> sysTagsArr = new ArrayList<>();
                                for (SysTagVo userTagVo : userTagVoList) {
                                    sysTagsArr.add(userTagVo.getId());
                                    SysTagShow sysTagShow = new SysTagShow();
                                    BeanUtils.copyProperties(userTagVo, sysTagShow);
                                    //查询标签名称
                                    MarketingTag marketingTag = marketingTagMapper.selectById(userTagVo.getId(), appUser.getMerId());
                                    if(marketingTag != null){
                                        sysTagShow.setName(marketingTag.getName());
                                    }
                                    sysTagShowList.add(sysTagShow);

                                }
                                appUserPageVo.setSysTagsArr(sysTagsArr);
                                appUserPageVo.setUserTagVoArr(sysTagShowList);
                            }
                        }catch (Exception e){ //如果不是JSON格式

                        }
                    }


                    //查询用户额外信息
                    UserExtInfoQueryDto userExtInfoQueryDto = new UserExtInfoQueryDto();
                    userExtInfoQueryDto.setMerId(appUserQuery.getMerId());
                    userExtInfoQueryDto.setDeviceType(DeviceTypeEnum.APP.getId()); //个人用户
                    userExtInfoQueryDto.setBizUserId(appUser.getBizUserId());
                    List<String> keys = new ArrayList<>();
                    keys.add("ValidOrderCount"); //首字母大写
                    userExtInfoQueryDto.setKeys(keys);
                    UzaiRespVo<EsUserExtInfo> uzaiRespVo = userExtInfoFeignService.getUserextinfo(userExtInfoQueryDto);
                    //logger.info("----订单总量----uzaiRespVo="+JSONObject.toJSONString(uzaiRespVo));

                    if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                        EsUserExtInfo esUserExtInfo = uzaiRespVo.getData();
                        if (esUserExtInfo != null) {
                            appUserPageVo.setOrderCount(esUserExtInfo.getValidOrderCount());
                        }
                    }
                    //是否在白名单当中
                    String id_white = appUserQuery.getMerId() + "_" + appUser.getBizUserId();
                    Map<String, Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
                    if (white_map != null) {
                        appUserPageVo.setBlacklistFlag(3); //白名单
                        appUserPageVo.setBlacklistId(appUser.getBizUserId());
                    }

                    //是否在全网黑名单当中
                    String id_blacklistPub = appUser.getBizUserId();
                    Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
                    if (pub_map != null) {
                        appUserPageVo.setBlacklistFlag(2); //共享全网黑名单
                        appUserPageVo.setBlacklistId(appUser.getBizUserId());
                    }

                    String id_blacklistPrv = appUserQuery.getMerId() + "_" + appUser.getBizUserId();
                    Map<String, Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
                    if (prv_map != null) { //在私有黑名单当中
                        appUserPageVo.setBlacklistFlag(1); //私有黑名单
                        appUserPageVo.setBlacklistId(id_blacklistPrv);
                    }
                } catch (Exception e) {

                }

                appUserPageVoList.add(appUserPageVo);
            }
        }

        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(appUserPageVoList);
        //将返回对象排序(如果没有，则默认id排序降序)
        if (StringUtils.isBlank(appUserQuery.getOrderByField()) && (appUserQuery.getOrderItemList() == null || appUserQuery.getOrderItemList().size() == 0)) {
            Tools.sort(appUserPageVoList, "id", appUserQuery.isAsc() ? "asc" : "desc");

        }
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 分页查询下级用户列表
     *
     * @param findSonUserListQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<AppUserPageVo> findSonUserList(AppFindSonUserListQuery findSonUserListQuery) {
        Long parentId = findSonUserListQuery.getParentId();
        if (parentId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入上级会员id");
        }

        Long merId = findSonUserListQuery.getMerId();
        if (merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        Integer type = Tools.getInteger(findSonUserListQuery.getType());

        AppUser appUser = appUserMapper.selectById(parentId, merId);
        if (appUser != null) {
            if (Tools.getInteger(appUser.getIdentity()).intValue() == IdentityEnum.BUYER.getId().intValue()) { //此会员是买家，则通过parentId来查询
                AppUserQuery appUserQuery = new AppUserQuery();
                BeanUtils.copyProperties(findSonUserListQuery, appUserQuery);
                appUserQuery.setMerId(findSonUserListQuery.getMerId());
                appUserQuery.setParentId(findSonUserListQuery.getParentId());
                appUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                return findWechatUserList(appUserQuery);
            } else if (Tools.getInteger(appUser.getIdentity()).intValue() == IdentityEnum.AGENT.getId().intValue()) {
                if (type == 2) { //下级代理
                    AppUserQuery appUserQuery = new AppUserQuery();
                    BeanUtils.copyProperties(findSonUserListQuery, appUserQuery);
                    appUserQuery.setParentId(null);
                    appUserQuery.setMerId(findSonUserListQuery.getMerId());
                    appUserQuery.setAgentId(findSonUserListQuery.getParentId());
                    appUserQuery.setIdentity(IdentityEnum.AGENT.getId()); //只查代理
                    return findWechatUserList(appUserQuery);
                } else if (type == 3 || type == 4) { //直推或者非直推买家
                    AppUserQuery appUserQuery = new AppUserQuery();
                    BeanUtils.copyProperties(findSonUserListQuery, appUserQuery);
                    appUserQuery.setParentId(null);
                    appUserQuery.setMerId(findSonUserListQuery.getMerId());
                    appUserQuery.setAgentId(findSonUserListQuery.getParentId());
                    appUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                    if (type == 3) { //直推
                        appUserQuery.setBuyerType(1);
                    } else {
                        appUserQuery.setBuyerType(2); //非直推
                    }
                    return findWechatUserList(appUserQuery);
                }
            } else { //合伙人
                if (type == 1) { //买家
                    AppUserQuery appUserQuery = new AppUserQuery();
                    BeanUtils.copyProperties(findSonUserListQuery, appUserQuery);
                    appUserQuery.setParentId(null);
                    appUserQuery.setMerId(findSonUserListQuery.getMerId());
                    appUserQuery.setPartnerId(findSonUserListQuery.getParentId());
                    appUserQuery.setIdentity(IdentityEnum.BUYER.getId()); //只查买家
                    return findWechatUserList(appUserQuery);
                } else if (type == 2) { //代理
                    AppUserQuery appUserQuery = new AppUserQuery();
                    BeanUtils.copyProperties(findSonUserListQuery, appUserQuery);
                    appUserQuery.setParentId(null);
                    appUserQuery.setMerId(findSonUserListQuery.getMerId());
                    appUserQuery.setPartnerId(findSonUserListQuery.getParentId());
                    appUserQuery.setIdentity(IdentityEnum.AGENT.getId()); //只查代理
                    return findWechatUserList(appUserQuery);
                }
            }
        }

        //返回到页面分页对象
        Page<AppUserPageVo> pageVo = new Page<>();
        BeanUtils.copyProperties(findSonUserListQuery, pageVo);
        return pageVo;
    }

    /**
     * 查询微信用户详情
     *
     * @param appUserIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public AppUserInfoVo findWechatUserInfo(@RequestBody AppUserIdDto appUserIdDto) {

        if (appUserIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //查询页面用户
        AppUser appUser = appUserMapper.selectById(appUserIdDto.getId(), appUserIdDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //返回给页面参数
        AppUserInfoVo appUserInfoVo = new AppUserInfoVo();
        BeanUtils.copyProperties(appUser, appUserInfoVo);

        //判断是否需要脱敏,默认脱敏
        Boolean tuominFlag = true;
        String CMSTYPE_WECHATUSER_WXID_VERIFIED = (String) redisTemplate.opsForValue().get(String.format(Const.SmsType.CMSTYPE_WECHATUSER_WXID_VERIFIED, appUserIdDto.getMerId(), appUserInfoVo.getId()));
        if (StringUtils.isNotBlank(CMSTYPE_WECHATUSER_WXID_VERIFIED)) {
            tuominFlag = false;
        }

        //是否脱敏处理
        if (tuominFlag) {
            appUserInfoVo.setWxid("");
        } else {
            appUserInfoVo.setWxid(appUser.getBizUserId());
        }

        //查询机器人ID
        if (appUser.getDeviceUniqueId() != null) {
            DeviceAppInfo deviceWechatInfo = deviceAppInfoMapper.selectById(appUser.getDeviceUniqueId(), appUser.getMerId());
            if (deviceWechatInfo != null) {
                appUserInfoVo.setDeviceId(deviceWechatInfo.getDeviceId());
                appUserInfoVo.setDeviceName(deviceWechatInfo.getDeviceName());
                appUserInfoVo.setDeviceRemark(deviceWechatInfo.getDeviceRemark());
            }
        }

        //用户类型组信息
        if (appUser.getUserType() != null) {
            UserType userType = userTypeMapper.selectById(appUser.getUserType(), appUserIdDto.getMerId());
            if (userType != null) {
                Long userTypeGroupId = userType.getGroupId();
                if (userTypeGroupId != null) {
                    UserTypeGroup userTypeGroup = userTypeGroupMapper.selectById(userTypeGroupId, appUserIdDto.getMerId());
                    if (userTypeGroup != null) {
                        appUserInfoVo.setUserTypeGroupId(userTypeGroup.getId());
                        appUserInfoVo.setUserTypeGroupName(userTypeGroup.getName());
                    }
                }
            }
        }

        //标签
        try {
            appUserInfoVo.setTagsArr(JSONObject.parseArray(appUser.getTags(), String.class));
        } catch (Exception e) { //如果不是JSON格式
        }


        //会员标签
        if(org.apache.commons.lang3.StringUtils.isNotBlank(appUser.getSysTags())){
            try {
                List<SysTagVo> userTagVoList =  JSONObject.parseArray(appUser.getSysTags(), SysTagVo.class);
                if(userTagVoList != null && userTagVoList.size() > 0){
                    List<SysTagShow> sysTagShowList = new ArrayList<>();
                    List<Long> sysTagsArr = new ArrayList<>();
                    for (SysTagVo userTagVo : userTagVoList) {
                        sysTagsArr.add(userTagVo.getId());
                        SysTagShow sysTagShow = new SysTagShow();
                        BeanUtils.copyProperties(userTagVo, sysTagShow);
                        //查询标签名称
                        MarketingTag marketingTag = marketingTagMapper.selectById(userTagVo.getId(), appUser.getMerId());
                        if(marketingTag != null){
                            sysTagShow.setName(marketingTag.getName());
                        }
                        sysTagShowList.add(sysTagShow);

                    }
                    appUserInfoVo.setSysTagsArr(sysTagsArr);
                    appUserInfoVo.setUserTagVoArr(sysTagShowList);
                }
            }catch (Exception e){ //如果不是JSON格式

            }
        }

        //上级、代理、合伙人如果为0，变成null
        if (appUserInfoVo.getParentId() != null && appUserInfoVo.getParentId().longValue() == 0) {
            appUserInfoVo.setParentId(null);
        }
        if (appUserInfoVo.getAgentId() != null && appUserInfoVo.getAgentId().longValue() == 0) {
            appUserInfoVo.setAgentId(null);
        }
        if (appUserInfoVo.getPartnerId() != null && appUserInfoVo.getPartnerId().longValue() == 0) {
            appUserInfoVo.setPartnerId(null);
        }

        //上级买家树
        if (StringUtils.isNotBlank(appUserInfoVo.getParentInfo())) {
            String parentInfo = appUserInfoVo.getParentInfo();
            //买家树长度
            int parentInfoLength = parentInfo.length();
            if (parentInfoLength > 19) {//长度大于19，上级不止一层，判断是否有下划线拼接
                //统计下划线的总数
                int underlineCount = Tools.stringContainCharTimes(parentInfo, "_");
                //计算上级买家树长度层级数
                int parentCount = (parentInfoLength - underlineCount) / 19;
                //判断计算出的买家树层级数与下划线的个数是否匹配，就是层数为下线线数+1
                if (parentCount == underlineCount + 1) { //如果买家数匹配上下划线数量，则不处理
                    String[] parentIdList = appUserInfoVo.getParentInfo().split("_");
                    if (parentIdList != null && parentIdList.length > 0) {
                        List<UserTreeVo> parentInfoList = new ArrayList<>();
                        for (String parentId : parentIdList) {
                            UserTreeVo userTreeVo = new UserTreeVo();
                            AppUser appUser_parent = appUserMapper.selectById(Long.valueOf(parentId), appUserIdDto.getMerId());
                            if (appUser_parent != null) {
                                userTreeVo.setId(appUser_parent.getId());
                                userTreeVo.setNickName(appUser_parent.getNickName());
                                parentInfoList.add(userTreeVo);
                            }
                        }
                        appUserInfoVo.setParentInfoList(parentInfoList);
                    }
                } else {//未匹配上，则需要清除下划线，重新修改买家树信息
                    parentInfo = parentInfo.replaceAll("_", "");
                    String[] parentIdList = Tools.stringToStringArray(parentInfo, 19);
                    if (parentIdList != null && parentIdList.length > 0) {
                        List<UserTreeVo> parentInfoList = new ArrayList<>();
                        for (String parentId : parentIdList) {
                            UserTreeVo userTreeVo = new UserTreeVo();
                            AppUser appUser_parent = appUserMapper.selectById(Long.valueOf(parentId), appUserIdDto.getMerId());
                            if (appUser_parent != null) {
                                userTreeVo.setId(appUser_parent.getId());
                                userTreeVo.setNickName(appUser_parent.getNickName());
                                parentInfoList.add(userTreeVo);
                            }
                        }
                        appUserInfoVo.setParentInfoList(parentInfoList);

                        //手动修改买家树
                        String parentInfoNew = StringUtils.join(parentIdList, "_");
                        appUser.setParentInfo(parentInfoNew);
                        appUserMapper.updateParetInfo(appUser);
                    }
                }
            } else {//就一层上级，没有下划线，直接查询该上级信息
                UserTreeVo userTreeVo = new UserTreeVo();
                AppUser appUser_parent = appUserMapper.selectById(Long.valueOf(parentInfo), appUserIdDto.getMerId());
                if (appUser_parent != null) {
                    List<UserTreeVo> parentInfoList = new ArrayList<>();
                    userTreeVo.setId(appUser_parent.getId());
                    userTreeVo.setNickName(appUser_parent.getNickName());
                    parentInfoList.add(userTreeVo);
                    appUserInfoVo.setParentInfoList(parentInfoList);
                }
            }
        }

        //上级代理树
        if (StringUtils.isNotBlank(appUserInfoVo.getAgentInfo())) {
            String[] agentIdList = appUserInfoVo.getAgentInfo().split("_");
            if (agentIdList != null && agentIdList.length > 0) {
                List<UserTreeVo> agentInfoList = new ArrayList<>();
                for (String agentId : agentIdList) {
                    UserTreeVo userTreeVo = new UserTreeVo();
                    AppUser appUser_agent = appUserMapper.selectById(Long.valueOf(agentId), appUserIdDto.getMerId());
                    if (appUser_agent != null) {
                        userTreeVo.setId(appUser_agent.getId());
                        userTreeVo.setNickName(appUser_agent.getNickName());
                        agentInfoList.add(userTreeVo);
                    }
                }
                appUserInfoVo.setAgentInfoList(agentInfoList);
            }
        }

        //是否在全网黑名单当中
        String id_blacklistPub = appUser.getBizUserId();
        Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, id_blacklistPub, null);
        if (pub_map != null) {
            appUserInfoVo.setBlacklistFlag(2); //共享全网黑名单
            appUserInfoVo.setBlacklistId(appUser.getBizUserId());
        }

        //是否在白名单当中
        String id_white = appUser.getMerId() + "_" + appUser.getBizUserId();
        Map<String, Object> white_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB_WHITE, id_white, null);
        if (white_map != null) {
            appUserInfoVo.setBlacklistFlag(3); //白名单
            appUserInfoVo.setBlacklistId(appUser.getBizUserId());
        }

        String id_blacklistPrv = appUser.getMerId() + "_" + appUser.getBizUserId();
        Map<String, Object> prv_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id_blacklistPrv, null);
        if (prv_map != null) { //在私有黑名单当中
            appUserInfoVo.setBlacklistFlag(1); //私有黑名单
            appUserInfoVo.setBlacklistId(id_blacklistPrv);
        }

        //会员互通信息
        if (StringUtils.isNotBlank(appUser.getUzaiUnionId())) {
            try {
                //互通的公众号会员信息
                WxpubUser wxpubUser = wxpubUserMapper.selectByUzaiUnionId(appUser.getUzaiUnionId(), appUser.getMerId());
                if (wxpubUser != null) {
                    appUserInfoVo.setWxpubUserId(wxpubUser.getId());
                }

                //互通的企业微信会员信息
                WxworkUser wxworkUser = wxworkUserMapper.selectByUzaiUnionId(appUser.getUzaiUnionId(), appUser.getMerId());
                if (wxworkUser != null) {
                    appUserInfoVo.setWxworkUserId(wxworkUser.getId());
                }
            } catch (Exception e) {
                logger.error("--通过unionId查询互通企业或者互通公众号出现异常--, uzaiUnionId={}", appUser.getUzaiUnionId());
            }

        }

        //如果会员昵称和会员头像都为空，则从ES中更新下信息
        if (StringUtils.isBlank(appUser.getNickName()) || StringUtils.isBlank(appUser.getHeadImg())) {
            //从ES中获取个人微信信息
            if (appUser.getDeviceUniqueId() != null) {
                DeviceAppInfo deviceWechatInfo = deviceAppInfoMapper.selectById(appUser.getDeviceUniqueId(), appUserIdDto.getMerId());
                if (deviceWechatInfo != null) {
                    if (StringUtils.isNotBlank(deviceWechatInfo.getDeviceId())) {
                        String esId = appUser.getMerId() + "_" + deviceWechatInfo.getDeviceId() + "_" + appUser.getBizUserId();
                        try {

                            //通过查询运营商其他索引分片获取分片索引
                            String uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(EsIndexName.UZAI_WX_CONTACTS, appUserIdDto.getMerId());
                            Map<String, Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, esId, null);
                            WxContactsInfoVo wxContactsInfoVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxContactsInfoVo.class);
                            if (wxContactsInfoVo != null) {
                                //更新微信信息
                                // appUser.setWxid(wxContactsInfoVo.getWxid());
                                appUser.setNickName(wxContactsInfoVo.getNick());
                                appUser.setHeadImg(wxContactsInfoVo.getHimg());
                                appUser.setRemark(wxContactsInfoVo.getRemark());
                                appUserMapper.updateById(appUser);

                                //返回给页面
                                // appUser.setWxid(wxContactsInfoVo.getWxid());
                                appUserInfoVo.setNickName(wxContactsInfoVo.getNick());
                                appUserInfoVo.setHeadImg(wxContactsInfoVo.getHimg());
                                appUserInfoVo.setRemark(wxContactsInfoVo.getRemark());
                            }
                        } catch (Exception e) {
                            logger.error("从ES中同步通讯录:error={}", e);
                        }
                    }
                }
            }
        }

        try {
            //关联其他机器人
            List<DeviceInfoVo> deviceInfoVoList = new ArrayList<>();
            appUserInfoVo.setDeviceInfoList(deviceInfoVoList);
            if (StringUtils.isNotBlank(appUser.getDeviceInfos())) {
                List<Long> deviceInfoList = JSONObject.parseArray(appUser.getDeviceInfos(), Long.class);
                if (deviceInfoList != null && deviceInfoList.size() > 0) {
                    for (Long deviceUniqueId : deviceInfoList) {
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(deviceUniqueId, DeviceTypeEnum.APP.getKey(), appUser.getMerId());
                        if (device != null) {
                            DeviceInfoVo deviceInfoVo = new DeviceInfoVo();
                            BeanUtils.copyProperties(device, deviceInfoVo);
                            deviceInfoVoList.add(deviceInfoVo);
                        }
                    }
                }
            }
        } catch (Exception e) {

        }

        try {
            //营销数据
            // TODO: 2023/4/6 待修改es名称
            String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
            String marketingRewardId = appUser.getId() + "" + appUser.getRegSource();
            Map<String, Object> dataMap = elasticsearchUtil.searchDataById(uzai_marketing_reward_info, marketingRewardId, null);
            MarketingRewardVo marketingRewardVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), MarketingRewardVo.class);
            if (marketingRewardVo == null) {
                marketingRewardVo = new MarketingRewardVo(true);
            }
            appUserInfoVo.setMarketingReward(marketingRewardVo);

        } catch (Exception e) {

        }

        //淘宝SID,默认查询第一条
        TbUserInfoQuery tbUserInfoQuery = new TbUserInfoQuery();
        tbUserInfoQuery.setMerId(appUser.getMerId());
        tbUserInfoQuery.setUserId(appUser.getId());
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(new Page<>(), tbUserInfoQuery);
        if(tbUserInfoList != null && tbUserInfoList.size() > 0){
            appUserInfoVo.setSpecialId(tbUserInfoList.get(0).getSpecialId());
        }


        return appUserInfoVo;
    }

    /**
     * 根据单个机器人群发消息
     *
     * @param appUserBatchSendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Integer groupSendMsgByDeviceUniqueId(AppUserBatchSendMsgDto appUserBatchSendMsgDto) {
        //记录成功发送总数
        int totalCount_son_succ = 0;

        //群发消息设置
        AppUserGroupSendMsgDto appUserGroupSendMsgDto = appUserBatchSendMsgDto.getWechatUserGroupSendMsgDto();
        //查询会员条件
        AppUserQuery appUserQuery = appUserBatchSendMsgDto.getWechatUserQuery();
        appUserQuery.setMerId(appUserBatchSendMsgDto.getMerId());
        if (appUserQuery == null) {//判断条件是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; appUserQuery is null");
            return totalCount_son_succ;
        }
        if (appUserQuery.getDeviceUniqueId() == null) {//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return totalCount_son_succ;
        }

        //查询数据库当中主任务是否存在
        if (appUserBatchSendMsgDto.getGroupSendJobParentId() == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParentId is null");
            return totalCount_son_succ;
        }

        DeviceAppInfo deviceWechatInfo = deviceAppInfoMapper.selectById(appUserQuery.getDeviceUniqueId(), appUserBatchSendMsgDto.getMerId());
        if (deviceWechatInfo == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceWechatInfo is null,  deviceUniqueId={}" + appUserQuery.getDeviceUniqueId());
            return totalCount_son_succ;
        }

        //免打扰时间
        Integer busyTimeInterval = appUserGroupSendMsgDto.getBusyTimeInterval();
        //页面设置了免打扰时间(页面填写的是天数)
        if (busyTimeInterval != null) {
            //免骚扰时间(针对群发消息用户过滤，这个时间发以后已经群发消息的用户不查询出来)= 现在时间-页面设置的免打扰时间
            Integer busyGroupSendMsgTime = appUserGroupSendMsgDto.getBeginTime() - busyTimeInterval * 3600;
            appUserQuery.setBusyGroupSendMsgTime(busyGroupSendMsgTime);
        }

        //查询这个机器人的所有会员-根据创建时间来分段查询
        //先查询创建时间最小得会员-然后根据10天内创建时间段来查询所有得会员
        AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
        //查询总数
        Integer count = appUserMapper.findCount(appUserQuery);
        //有总数
        if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
            int now = DateUtil.getNowTime();
            //添加群发消息子任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(appUserBatchSendMsgDto.getGroupSendJobParentId()); //主任务id
            groupSendJob_son.setMerId(appUserBatchSendMsgDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.APP.getKey());
            groupSendJob_son.setDeviceUniqueId(appUserQuery.getDeviceUniqueId());
            groupSendJob_son.setName(appUserGroupSendMsgDto.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.APP_USER.getId());
            groupSendJob_son.setContent(Tools.getStr(appUserGroupSendMsgDto.getContent()));
            groupSendJob_son.setStatus(GroupSendStatusEnum.INIT.getValue());
            groupSendJob_son.setTotalCount(count); //默认消息数
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(appUserGroupSendMsgDto.getTimeInterval());
            groupSendJob_son.setBeginTime(appUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setExptime(now + 15 * 24 * 3600); //当前时间之后的15天内
            groupSendJob_son.setUserLab(Tools.getStrEmpty(JSONObject.toJSONString(appUserGroupSendMsgDto.getUserLabList())));
            groupSendJob_son.setCleanLab(appUserGroupSendMsgDto.getCleanLab());
            groupSendJob_son.setUserRemark(Tools.getStr(appUserGroupSendMsgDto.getUserRemark()));
            groupSendJob_son.setNightTime(appUserGroupSendMsgDto.getNightTime());
            groupSendJob_son.setBusyTimeInterval(appUserGroupSendMsgDto.getBusyTimeInterval());
            groupSendJob_son.setSendStartTime(appUserGroupSendMsgDto.getBeginTime());
            groupSendJob_son.setIgnoreName(Tools.getStrEmpty(JSONObject.toJSONString(appUserQuery.getNameExcludeList())));
            groupSendJob_son.setIgnoreRemark(Tools.getStrEmpty(JSONObject.toJSONString(appUserQuery.getRemarkExcludeList())));
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            try {
                //延迟时间
                int delay = 0;//循环累加延迟时间
                //则循环查询5天内的创建的会员
                int duration = 10 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        //每个时间段分页查询，每页10个
                        Page<AppUserSimpleVo> page = new Page<>();
                        int current = 1;
                        page.setCurrent(current);
                        page.setSize(10);//最大支持10，如果此时间段数据大于10，则分页查询
                        List<AppUserSimpleVo> appUserSimpleVoList = appUserMapper.findSimpleByList(page, appUserQuery);
                        while (appUserSimpleVoList != null && appUserSimpleVoList.size() > 0) {
                            try {
                                List<NewGroupSendMsgDto> groupSendMsgDtoList = new ArrayList<>();
                                //发送消息
                                for (AppUserSimpleVo appUserSimpleVo : appUserSimpleVoList) {
                                    //发送MQ消息
                                    NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                                    newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                                    newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                                    String msg = Tools.getStr(groupSendJob_son.getContent());
                                    msg = msg.replace("[随机表情]", Tools.getStr(EmojiUtil.getRandomEmoji()))
                                            .replace("[昵称]", Tools.getStr(appUserSimpleVo.getNickName()));
                                    newGroupSendMsgDto.setMsg(msg);
                                    newGroupSendMsgDto.setMerId(appUserSimpleVo.getMerId());
                                    newGroupSendMsgDto.setDeviceUniqueId(appUserSimpleVo.getDeviceUniqueId());
                                    newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                                    newGroupSendMsgDto.setDeviceType(DeviceTypeEnum.APP.getId());
                                    newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                                    newGroupSendMsgDto.setUserId(appUserSimpleVo.getId());
                                    newGroupSendMsgDto.setBizUserId(appUserSimpleVo.getBizUserId());
                                    newGroupSendMsgDto.setNickName(appUserSimpleVo.getNickName());
                                    newGroupSendMsgDto.setDelay(delay);
                                    newGroupSendMsgDto.setOriginalDelay(delay);
                                    delay = delay + appUserGroupSendMsgDto.getTimeInterval(); //循环累加延迟时间
                                    newGroupSendMsgDto.setRetry(0);
                                    newGroupSendMsgDto.setLabel(groupSendJob_son.getUserLab());
                                    newGroupSendMsgDto.setCleanLab(groupSendJob_son.getCleanLab());
                                    String remark = Tools.getStr(groupSendJob_son.getUserRemark());
                                    remark = remark.replace("[昵称]", Tools.getStr(appUserSimpleVo.getNickName()))
                                            .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                                    newGroupSendMsgDto.setRemark(remark);
                                    groupSendMsgDtoList.add(newGroupSendMsgDto);
                                }

                                //群发消息
                                if (groupSendMsgDtoList.size() > 0) {
                                    UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                                    if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                                        totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                        logger.info("----查询结果群发消息调用微服务推送消息---para={}, size={}, result={}", JSONObject.toJSONString(appUserQuery), groupSendMsgDtoList.size(), JSONObject.toJSONString(uzaiRespVo));
                                    } else {
                                        //失败的在调用一次,再次失败则修改群发消息条数
                                        UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                                        if (uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                            logger.info("---查询结果群发消息第二次调用微服务推送消息成功---msg={}", uzaiRespVo_repeat.getMsg());
                                            totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                        } else {
                                            logger.error("---查询结果群发消息第二次调用微服务推送消息---error={}", uzaiRespVo_repeat.getMsg());
                                        }
                                    }
                                }
                            } catch (Exception e) {
                                logger.error("---查询结果群发消息异常---error={}", e.getMessage());
                            }

                            //再次查询下一页
                            current++;
                            page.setCurrent(current);
                            appUserSimpleVoList = appUserMapper.findSimpleByList(page, appUserQuery);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("---个人微信会员群发消息异常---deviceUniqueId={},msg={}", appUserQuery.getDeviceUniqueId(), e.getMessage());
            }

            //修改子任务发送总数
            //groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount(totalCount_son_succ);
            groupSendJobMapper.updateTotalCountById(groupSendJob_son);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJob_son.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJob_son.getTimeInterval());
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));
        }

        return totalCount_son_succ;

    }

    /**
     * (多选框选择会员)根据单个机器人群发消息(异步)
     *
     * @param appUserSendMsgBatchDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Integer groupSendMsgByDeviceUniqueIdBatch(AppUserSendMsgBatchDto appUserSendMsgBatchDto) {

        //记录子任务成功发送总数
        int totalCount_son_succ = 0;

        //查询这个机器人的所有会员
        List<Long> idList = appUserSendMsgBatchDto.getIdList();
        if (idList == null || idList.size() == 0) {
            logger.error("--groupSendMsgByDeviceUniqueIdBatch is error; idList is null");
            return totalCount_son_succ;
        }

        //获取群发消息任务内容
        AppUserGroupSendMsgDto groupSendMsgDto = appUserSendMsgBatchDto.getWechatUserGroupSendMsgDto();
        groupSendMsgDto.setMerId(appUserSendMsgBatchDto.getMerId());
        if (groupSendMsgDto == null) {
            return totalCount_son_succ;
        }

        if (appUserSendMsgBatchDto.getDeviceUniqueId() == null) {//判断机器人是否为空
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceUniqueId is null");
            return totalCount_son_succ;
        }

        //查询数据库当中主任务是否存在
        if (appUserSendMsgBatchDto.getGroupSendJobParentId() == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; groupSendJobParentId is null");
            return totalCount_son_succ;
        }

        DeviceAppInfo deviceWechatInfo = deviceAppInfoMapper.selectById(appUserSendMsgBatchDto.getDeviceUniqueId(), appUserSendMsgBatchDto.getMerId());
        if (deviceWechatInfo == null) {
            logger.error("--groupSendMsgByDeviceUniqueId is error; deviceWechatInfo is null,  deviceUniqueId={}" + appUserSendMsgBatchDto.getDeviceUniqueId());
            return totalCount_son_succ;
        }

        //封装该机器人下的会员
        List<AppUser> appUserList = new ArrayList<>();
        if (idList != null && idList.size() > 0) {
            for (Long id : idList) {
                AppUser appUser = appUserMapper.selectById(id, appUserSendMsgBatchDto.getMerId());
                if (appUser.getDeviceUniqueId().longValue() == deviceWechatInfo.getId().longValue()) { //匹配该机器人的用户
                    appUserList.add(appUser);
                }
            }
        }

        if (appUserList != null && appUserList.size() > 0) {
            Integer now = DateUtil.getNowTime();
            //添加群发消息子任务
            GroupSendJob groupSendJob_son = new GroupSendJob();
            groupSendJob_son.setId(IdWorker.getId());
            groupSendJob_son.setParentId(appUserSendMsgBatchDto.getGroupSendJobParentId()); //主任务id
            groupSendJob_son.setMerId(appUserSendMsgBatchDto.getMerId());
            groupSendJob_son.setDeviceType(DeviceTypeEnum.APP.getKey());
            groupSendJob_son.setDeviceUniqueId(appUserSendMsgBatchDto.getDeviceUniqueId());
            groupSendJob_son.setName(groupSendMsgDto.getName());
            groupSendJob_son.setSource(GroupSendJobSourceEnum.APP_USER.getId());
            groupSendJob_son.setContent(Tools.getStr(groupSendMsgDto.getContent()));
            groupSendJob_son.setStatus(GroupSendStatusEnum.INIT.getValue());
            groupSendJob_son.setTotalCount(appUserList.size());
            groupSendJob_son.setFinishCount(0);
            groupSendJob_son.setTimeInterval(groupSendMsgDto.getTimeInterval());
            groupSendJob_son.setBeginTime(groupSendMsgDto.getBeginTime());
            groupSendJob_son.setExptime(now + 15 * 24 * 3600); //当前时间之后的15天内
            groupSendJob_son.setUserLab(Tools.getStrEmpty(JSONObject.toJSONString(groupSendMsgDto.getUserLabList())));
            groupSendJob_son.setCleanLab(groupSendMsgDto.getCleanLab());
            groupSendJob_son.setUserRemark(Tools.getStr(groupSendMsgDto.getUserRemark()));
            groupSendJob_son.setNightTime(groupSendMsgDto.getNightTime());
            groupSendJob_son.setBusyTimeInterval(groupSendMsgDto.getBusyTimeInterval());
            groupSendJob_son.setSendStartTime(groupSendMsgDto.getBeginTime());
            groupSendJob_son.setCreateTime(now);
            groupSendJob_son.setUpdateTime(now);
            groupSendJobMapper.insertSelective(groupSendJob_son);

            //群发消息
            try {

                //延迟时间
                int delay = 0;//循环累加延迟时间
                //发送消息
                List<NewGroupSendMsgDto> groupSendMsgDtoList = new ArrayList<>();
                for (AppUser appUser : appUserList) {
                    if (appUser != null) {
                        //发送MQ消息
                        NewGroupSendMsgDto newGroupSendMsgDto = new NewGroupSendMsgDto();
                        newGroupSendMsgDto.setParentJobId(groupSendJob_son.getParentId());
                        newGroupSendMsgDto.setChildJobId(groupSendJob_son.getId());
                        String msg = Tools.getStr(groupSendJob_son.getContent());
                        msg = msg.replace("[随机表情]", Tools.getStr(EmojiUtil.getRandomEmoji()))
                                .replace("[昵称]", Tools.getStr(appUser.getNickName()));
                        newGroupSendMsgDto.setMsg(msg);
                        newGroupSendMsgDto.setMerId(appUser.getMerId());
                        newGroupSendMsgDto.setDeviceUniqueId(appUser.getDeviceUniqueId());
                        newGroupSendMsgDto.setDeviceId(deviceWechatInfo.getDeviceId());
                        newGroupSendMsgDto.setDeviceType(DeviceTypeEnum.APP.getId());
                        newGroupSendMsgDto.setMsgType(MessageTypeEnum.MT_TEXT.getValue());
                        newGroupSendMsgDto.setUserId(appUser.getId());
                        newGroupSendMsgDto.setBizUserId(appUser.getBizUserId());
                        newGroupSendMsgDto.setNickName(appUser.getNickName());
                        newGroupSendMsgDto.setDelay(delay);
                        newGroupSendMsgDto.setOriginalDelay(delay);
                        delay = delay + groupSendMsgDto.getTimeInterval(); //循环累加延迟时间
                        newGroupSendMsgDto.setRetry(0);
                        newGroupSendMsgDto.setLabel(Tools.getStrEmpty(JSONObject.toJSONString(groupSendMsgDto.getUserLabList())));
                        newGroupSendMsgDto.setCleanLab(groupSendMsgDto.getCleanLab());
                        String remark = Tools.getStr(groupSendMsgDto.getUserRemark());
                        remark = remark.replace("[昵称]", Tools.getStr(appUser.getNickName()))
                                .replace("[群发时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                        newGroupSendMsgDto.setRemark(remark);
                        groupSendMsgDtoList.add(newGroupSendMsgDto);
                    }

                    //大于10个消息就发送一次，发送成功就清空该列表
                    if (groupSendMsgDtoList != null && groupSendMsgDtoList.size() >= 10) {
                        UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                        if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                            logger.info("----手动选择会员群发调用微服务推送消息成功---para={},result={}", JSONObject.toJSONString(groupSendMsgDtoList), JSONObject.toJSONString(uzaiRespVo));
                            totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                            //清空发送消息
                            groupSendMsgDtoList.clear();
                        } else {
                            //失败的在调用一次,再次失败则修改群发消息条数
                            UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                            if (uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                                logger.info("----手动选择会员群发第二次调用微服务推送成功---msg={}", uzaiRespVo_repeat.getMsg());
                                totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                                //清空发送消息
                                groupSendMsgDtoList.clear();
                            } else {
                                logger.error("----手动选择会员群发第二次调用微服务推送消息失败---error={}", uzaiRespVo_repeat.getMsg());
                            }
                        }
                    }
                }

                //最后在统一发送剩余的消息
                if (groupSendMsgDtoList != null && groupSendMsgDtoList.size() > 0) {
                    UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                    if (uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                        logger.info("----手动选择会员群发调用微服务推送消息成功---para={},result={}", JSONObject.toJSONString(groupSendMsgDtoList), JSONObject.toJSONString(uzaiRespVo));
                        totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                        //清空发送消息
                        groupSendMsgDtoList.clear();
                    } else {
                        logger.info("----手动选择会员群发第二次调用微服务推送消息---error={}", uzaiRespVo.getMsg());
                        //失败的在调用一次,再次失败则修改群发消息条数
                        UzaiRespVo<Boolean> uzaiRespVo_repeat = uzaiBroadcastFeignService.groupSendMsgPush(groupSendMsgDtoList);
                        if (uzaiRespVo_repeat != null && uzaiRespVo_repeat.getCode() == 200) {
                            logger.info("----手动选择会员群发第二次调用微服务推送成功---msg={}", uzaiRespVo_repeat.getMsg());
                            totalCount_son_succ = totalCount_son_succ + groupSendMsgDtoList.size();
                            //清空发送消息
                            groupSendMsgDtoList.clear();
                        } else {
                            logger.error("----手动选择会员群发第二次调用微服务推送消息失败---error={}", uzaiRespVo_repeat.getMsg());
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("---个人微信会员群发消息异常---deviceUniqueId={},msg={}", appUserSendMsgBatchDto.getDeviceUniqueId(), e.getMessage());
            }

            //修改子任务发送总数
            //groupSendJob_son.setStatus(GroupSendStatusEnum.NOT_START.getValue());
            groupSendJob_son.setTotalCount(totalCount_son_succ);
            groupSendJobMapper.updateTotalCountById(groupSendJob_son);

            //推送子任务
            GroupSendChildidPushDto groupSendChildidPushDto = new GroupSendChildidPushDto();
            groupSendChildidPushDto.setChildJobId(groupSendJob_son.getId());
            groupSendChildidPushDto.setTimeInterval(groupSendJob_son.getTimeInterval());
            UzaiRespVo<Boolean> uzaiRespVo = uzaiBroadcastFeignService.groupSendChildIdPush(groupSendChildidPushDto);
            logger.info("推送群发消息子任务,dto={}, result={}", JSONObject.toJSONString(groupSendChildidPushDto), JSONObject.toJSONString(uzaiRespVo));
        }

        return totalCount_son_succ;

    }

    /**
     * 删除用户信息
     *
     * @param id
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteUserById(Long id, Long merId) {
        AppUser appUser = appUserMapper.selectById(id, merId);
        if (appUser == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        int now = DateUtil.getNowTime();

        //真删除
        appUserMapper.deleteById(id, merId);

        //删除缓存
        redisTemplate.delete(String.format(RedisCacheKeyEnum.APP_USER_ID.getKey(), merId, appUser.getBizUserId()));

        //删除ES
        try {
            //删除会员基本信息
            String uzai_user_info_id = DeviceTypeEnum.APP.getKey() + "_" + appUser.getMerId() + "_" + appUser.getBizUserId();
            String uzai_user_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_INFO, appUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_info, uzai_user_info_id);

            //删除会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.APP.getKey() + "_" + appUser.getMerId() + "_" + appUser.getBizUserId();
            String uzai_user_ext_info = merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, appUser.getMerId());
            elasticsearchUtil.deleteDataById(uzai_user_ext_info, uzai_user_ext_info_id);

            //删除营销奖励信息
            String uzai_user_marketing_reward_info_id = appUser.getId() + "" + appUser.getRegSource();
            elasticsearchUtil.deleteDataById(EsIndexName.UZAI_MARKETING_REWARD_INFO, uzai_user_marketing_reward_info_id);

        } catch (Exception e) {
            logger.error("删除ES会员扩展信息出现异常:{}" + e.getMessage());
        }


        //根据此会员的身份来查询下级用户
        if (appUser.getIdentity().intValue() == IdentityEnum.BUYER.getId()) { //此会员是买家
            //查询所有下级买家
            AppUserQuery appUserQuery = new AppUserQuery();
            appUserQuery.setMerId(appUser.getMerId());
            appUserQuery.setParentId(appUser.getId());
            //查询总数
            Integer count = appUserMapper.findCount(appUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<AppUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<AppUser> appUserList = appUserMapper.findByList(page, appUserQuery);
                    if(appUserList != null && appUserList.size() > 0){
                        for(AppUser appUser_son : appUserList) {
                            try {
                                //旧上级树
                                String parentInfoOld_Nson = appUser_son.getParentInfo();
                                //将此会员的上级清空
                                appUser_son.setParentId(0L);
                                appUser_son.setParentInfo("");
                                appUserMapper.updateIdentityInfo(appUser_son);
                                //批量替换清空
                                appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "", appUser_son.getMerId(), true);
                                appUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, "", appUser_son.getMerId(), false);
                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", appUser_son.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

//            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//            AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
//            //查询总数
//            Integer count = appUserMapper.findCount(appUserQuery);
//            //有总数，且最小创建时间有
//            if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//                //则循环查询5天内的创建的会员
//                int duration = 5 * 24 * 3600;
//                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//                if (timeVOList != null && timeVOList.size() > 0) {
//                    for (TimeVO timeVO : timeVOList) {
//                        appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                        appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//                        List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
//                        if (appUserList != null && appUserList.size() > 0) {
//                            for (AppUser appUser_son : appUserList) {
//                                //旧上级树
//                                String parentInfoOld_Nson = appUser_son.getParentInfo();
//                                //将此会员的上级清空
//                                appUser_son.setParentId(0L);
//                                appUser_son.setParentInfo("");
//                                appUserMapper.updateIdentityInfo(appUser_son);
//                                //批量替换清空
//                                appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "", appUser_son.getMerId(), true);
//                                appUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, "", appUser_son.getMerId(), false);
//                            }
//                        }
//                    }
//                }
//            }
        } else if (appUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//代理身份
            //查询所有下级代理
            AppUserQuery appUserQuery = new AppUserQuery();
            appUserQuery.setMerId(appUser.getMerId());
            appUserQuery.setAgentId(appUser.getId());

            //查询总数
            Integer count = appUserMapper.findCount(appUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<AppUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<AppUser> appUserList = appUserMapper.findByList(page, appUserQuery);
                    if(appUserList != null && appUserList.size() > 0){
                        for(AppUser appUser_son : appUserList) {
                            try {
                                //旧代理树
                                String agentInfoOld_Nson = appUser_son.getAgentInfo();
                                //将此会员的代理信息给下级代理
                                appUser_son.setAgentId(0L);
                                appUser_son.setAgentInfo("");
                                appUserMapper.updateIdentityInfo(appUser_son);
                                //批量替换
                                appUserMapper.batchUpdateParentInfo("_" + agentInfoOld_Nson, "", appUser_son.getMerId(), true);
                                appUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, "", appUser_son.getMerId(), false);

                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", appUser_son.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

//            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//            AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
//            //查询总数
//            Integer count = appUserMapper.findCount(appUserQuery);
//            //有总数，且最小创建时间有
//            if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//                //则循环查询5天内的创建的会员
//                int duration = 5 * 24 * 3600;
//                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//                if (timeVOList != null && timeVOList.size() > 0) {
//                    for (TimeVO timeVO : timeVOList) {
//                        appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                        appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//                        List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
//                        if (appUserList != null && appUserList.size() > 0) {
//                            for (AppUser appUser_son : appUserList) {
//                                //旧代理树
//                                String agentInfoOld_Nson = appUser_son.getAgentInfo();
//                                //将此会员的代理信息给下级代理
//                                appUser_son.setAgentId(0L);
//                                appUser_son.setAgentInfo("");
//                                appUserMapper.updateIdentityInfo(appUser_son);
//                                //批量替换
//                                appUserMapper.batchUpdateParentInfo("_" + agentInfoOld_Nson, "", appUser_son.getMerId(), true);
//                                appUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, "", appUser_son.getMerId(), false);
//
//                            }
//                        }
//                    }
//                }
//            }
        } else if (appUser.getIdentity().intValue() == IdentityEnum.AGENT.getId()) {//合伙人身份
            //查询所有下级代理
            AppUserQuery appUserQuery = new AppUserQuery();
            appUserQuery.setMerId(appUser.getMerId());
            appUserQuery.setPartnerId(appUser.getId());

            //查询总数
            Integer count = appUserMapper.findCount(appUserQuery);
            //每页个数
            int size = 10;
            if(Tools.getInteger(count) > 0 ){
                int totalPage = count / size + 1; //总页数
                for(int i = totalPage ; i>0;  i--){
                    //每个时间段分页查询，每页200个
                    Page<AppUser> page = new Page<>();
                    page.setCurrent(i);
                    page.setSize(size);
                    List<AppUser> appUserList = appUserMapper.findByList(page, appUserQuery);
                    if(appUserList != null && appUserList.size() > 0){
                        for(AppUser appUser_son : appUserList) {
                            try {
                                //清空合伙人
                                appUser_son.setPartnerId(0L);
                                appUserMapper.updateIdentityInfo(appUser_son);
                            } catch (Exception e) {
                                logger.error("-------deleteUserById is error userId={}, error={}", appUser_son.getId(), e.getMessage());
                            }
                        }
                    }
                }
            }

//            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
//            AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
//            //查询总数
//            Integer count = appUserMapper.findCount(appUserQuery);
//            //有总数，且最小创建时间有
//            if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
//                //则循环查询5天内的创建的会员
//                int duration = 5 * 24 * 3600;
//                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
//                if (timeVOList != null && timeVOList.size() > 0) {
//                    for (TimeVO timeVO : timeVOList) {
//                        appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
//                        appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
//                        List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
//                        if (appUserList != null && appUserList.size() > 0) {
//                            for (AppUser appUser_son : appUserList) {
//                                //清空合伙人
//                                appUser_son.setPartnerId(0L);
//                                appUserMapper.updateIdentityInfo(appUser_son);
//                            }
//                        }
//                    }
//                }
//            }
        }
    }

    /**
     * 删除上下级会员关系
     *
     * @param appUserDeleteSonDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteSonWechatUser(AppUserDeleteSonDto appUserDeleteSonDto) {

        Long merId = appUserDeleteSonDto.getMerId();
        Long id = appUserDeleteSonDto.getId();
        Integer identity = appUserDeleteSonDto.getIdentity();

        if (identity == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "身份参数不能为空");
        }

        AppUser appUser = appUserMapper.selectById(id, merId);
        if (appUser == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "用户不存在");
        }

        //根据此会员的身份来查询下级用户
        if (identity.intValue() == IdentityEnum.BUYER.getId().intValue()) { //此会员是买家
            //清理上级买家关系
            appUser.setParentId(0L);
            appUser.setParentInfo("");
            appUserMapper.updateIdentityInfo(appUser);

            //查询所有下级买家
            AppUserQuery appUserQuery = new AppUserQuery();
            appUserQuery.setMerId(appUser.getMerId());
            appUserQuery.setParentId(appUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
            //查询总数
            Integer count = appUserMapper.findCount(appUserQuery);
            //有总数，且最小创建时间有
            if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
                        if (appUserList != null && appUserList.size() > 0) {
                            for (AppUser appUser_son : appUserList) {
                                //旧上级树
                                String parentInfoOld_Nson = appUser_son.getParentInfo();
                                //将此会员的上级树修改为上级的id
                                appUser_son.setParentInfo(String.valueOf(appUser.getId()));
                                appUserMapper.updateIdentityInfo(appUser_son);
                                //批量替换清空
                                appUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, String.valueOf(appUser.getId()), appUser.getMerId(), false);
                            }
                        }
                    }
                }
            }
        } else if (identity.intValue() == IdentityEnum.AGENT.getId().intValue()) {//代理身份

            //清理上级代理关系
            appUser.setAgentId(0L);
            appUser.setAgentInfo("");
            appUserMapper.updateIdentityInfo(appUser);

            //查询所有下级代理
            AppUserQuery appUserQuery = new AppUserQuery();
            appUserQuery.setMerId(appUser.getMerId());
            appUserQuery.setAgentId(appUser.getId());

            //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
            AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
            //查询总数
            Integer count = appUserMapper.findCount(appUserQuery);
            //有总数，且最小创建时间有
            if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                //则循环查询5天内的创建的会员
                int duration = 5 * 24 * 3600;
                List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                if (timeVOList != null && timeVOList.size() > 0) {
                    for (TimeVO timeVO : timeVOList) {
                        appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                        appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                        List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
                        if (appUserList != null && appUserList.size() > 0) {
                            for (AppUser appUser_son : appUserList) {
                                //旧代理树
                                String agentInfoOld_Nson = appUser_son.getAgentInfo();
                                //将此会员的代理信息给下级代理
                                appUser_son.setAgentInfo(String.valueOf(appUser.getId()));
                                appUserMapper.updateIdentityInfo(appUser_son);
                                //批量替换
                                appUserMapper.batchUpdateParentInfo(agentInfoOld_Nson, String.valueOf(appUser.getId()), appUser.getMerId(), false);
                            }
                        }
                    }
                }
            }
        } else if (identity.intValue() == IdentityEnum.PARTNER.getId().intValue()) {//合伙人
            //清理合伙人关系
            appUser.setPartnerId(0L);
            appUserMapper.updateIdentityInfo(appUser);
        }

        //修改ES缓存
        //修改ES
        try {

            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.APP.getKey() + "_" + appUser.getMerId() + "_" + appUser.getBizUserId();
            //查询会员基本信息
            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, appUser.getMerId()), uzai_user_ext_info_id, null);
            if (dataMp_ext != null) {
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(appUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, appUser.getMerId()), uzai_user_ext_info_id);
            }

        } catch (Exception e) {
            logger.error("修改会员营销策略信息出现异常:{}" + e.getMessage());
        }

    }

    /**
     * 分页查询微信用户账户明细列表
     *
     * @param userAccDetailQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<UserAccDetailInfoVo> findWechatUserAccDetailList(UserAccDetailQuery userAccDetailQuery) {

        //用户ID不能为空，必须指定用户
        if (userAccDetailQuery.getUserId() == null) {
            throw new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请指定用户进行查询");
        }

        //新建返回到页面的LIST对象
        List<UserAccDetailInfoVo> appUserAccDetailInfoVoList = new ArrayList<UserAccDetailInfoVo>();
        //执行分页查询对象
        Page<UserAccDetail> page = new Page<>();
        userAccDetailQuery.convert(page);
        List<UserAccDetail> userAccDetailList = null;
        if (super.checkStartEndTimeIsHistoryQuery(userAccDetailQuery.getQueryStartTime(), userAccDetailQuery.getQueryEndTime(), null)) {
            String tableSuffix = DateTime.of(userAccDetailQuery.getQueryEndTime() * 1000L).toString("yyMM");
            UzaiRespVo<Page<UserAccDetail>> listUzaiRespVoRes = historyDataFeignService.searchAccDetail(tableSuffix, userAccDetailQuery);
            if (listUzaiRespVoRes.getCode() != 200) {
                throw new BusinessException("提现列表查询失败");
            }
            if(listUzaiRespVoRes.getData() != null){
                userAccDetailList = listUzaiRespVoRes.getData().getRecords();
                page.setTotal(listUzaiRespVoRes.getData().getTotal());
            }
        }
        // 反之查询90天内的订单数据
        else {
            userAccDetailList = userAccDetailMapper.findByList(page, userAccDetailQuery);
        }

        if (userAccDetailList != null) {
            for (UserAccDetail appUserAccDetail : userAccDetailList) {
                UserAccDetailInfoVo appUserAccDetailInfoVo = new UserAccDetailInfoVo();
                BeanUtils.copyProperties(appUserAccDetail, appUserAccDetailInfoVo);
                //用户昵称
                AppUser appUser = appUserMapper.selectById(appUserAccDetail.getUserId(), userAccDetailQuery.getMerId());
                if (appUser != null) {
                    appUserAccDetailInfoVo.setNickName(appUser.getNickName());
                }
                //明细类型
                appUserAccDetailInfoVo.setTypeName(AccDetailTypeEnum.getById(appUserAccDetail.getType()).getDesc());

                //订单编号商户订单号
                appUserAccDetailInfoVo.setOrderIdTradeno(Tools.getStr(appUserAccDetail.getOrderId()) + "/" + Tools.getStr(appUserAccDetail.getTradeno()));
                appUserAccDetailInfoVoList.add(appUserAccDetailInfoVo);
            }
        }
        //返回到页面分页对象
        Page<UserAccDetailInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(appUserAccDetailInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 分页查询用户会员渠道ID列表
     *
     * @param tbUserInfoQuery
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public Page<TbUserInfoVo> findTbUserInfoList(TbUserInfoQuery tbUserInfoQuery) {
        //新建返回到页面的LIST对象
        List<TbUserInfoVo> tbUserInfoVoList = new ArrayList<TbUserInfoVo>();
        //执行分页查询对象
        Page<TbUserInfo> page = new Page<>();
        tbUserInfoQuery.convert(page);
        List<TbUserInfo> tbUserInfoList = tbUserInfoMapper.findByList(page, tbUserInfoQuery);
        if (tbUserInfoList != null) {
            for (TbUserInfo tbUserInfo : tbUserInfoList) {
                TbUserInfoVo tbUserInfoVo = new TbUserInfoVo();
                BeanUtils.copyProperties(tbUserInfo, tbUserInfoVo);
                //用户昵称
                TbToken tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbUserInfo.getTbTokenId(),0);
                if(tbToken == null){
                    tbToken = tbTokenMapper.selectByUserIdAndTurnLink(tbUserInfo.getTbTokenId(), 1);
                }
                if (tbToken != null) {
                    tbUserInfoVo.setTbTokenName(tbToken.getUserName());
                }
                tbUserInfoVoList.add(tbUserInfoVo);
            }
        }
        //返回到页面分页对象
        Page<TbUserInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(tbUserInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 修改会员渠道ID
     *
     * @param tbUserInfoUpdateDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateTbUserInfo(TbUserInfoUpdateDto tbUserInfoUpdateDto) {
        if (tbUserInfoUpdateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        TbUserInfo tbUserInfo = tbUserInfoMapper.selectById(tbUserInfoUpdateDto.getId(), tbUserInfoUpdateDto.getMerId());
        tbUserInfo.setSpecialId(tbUserInfoUpdateDto.getSpecialId());
        tbUserInfo.setRelationId(tbUserInfoUpdateDto.getRelationId());
        tbUserInfo.setUpdateTime(DateUtil.getNowTime());
        tbUserInfoMapper.updateById(tbUserInfo);
    }

    /**
     * 删除会员渠道ID
     *
     * @param tbUserInfoIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void deleteTbUserInfo(TbUserInfoIdDto tbUserInfoIdDto) {
        if (tbUserInfoIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        tbUserInfoMapper.deleteById(tbUserInfoIdDto.getId(), tbUserInfoIdDto.getMerId());
    }


    /**
     * 修改微信用户积分余额
     *
     * @param updateBalanceDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateWechatUserBalance(AppUserUpdateBalanceDto updateBalanceDto) {


        if(updateBalanceDto.getId() == null || updateBalanceDto.getBalance() ==null || updateBalanceDto.getIntegral() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        //至少要修改一个
        if(updateBalanceDto.getBalance() == null && updateBalanceDto.getIntegral() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分和余额至少要修改一项");
        }

        //修改值不能为负数
        if(Tools.getDouble(updateBalanceDto.getBalance()).doubleValue() <  0 || Tools.getInteger(updateBalanceDto.getIntegral()).intValue() < 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "只能输入大于0的数");
        }

        if(org.apache.commons.lang3.StringUtils.isNotBlank(updateBalanceDto.getRemark())){
            //判断是否包括表情
            if(EmojiUtil.containsEmoji(updateBalanceDto.getRemark())){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "原因不能包含表情符号");
            }
        }

        AppUser appUser = appUserMapper.selectById(updateBalanceDto.getId(), updateBalanceDto.getMerId());
        if(appUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员余额和积分;");

        //变更余额
        Double balance = updateBalanceDto.getBalance();
        Double changeBalance = 0.0D;
        //表示修改余额
        if(balance != null){
            //修改类型类型
            Integer balanceType = updateBalanceDto.getBalanceType();
            if(balanceType == null){ //修改余额
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入余额修改类型");
            }
            if(!Lists.newArrayList(-1,0,1).contains(balanceType)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "余额修改类型值有误");
            }

            //旧余额
            Double oldBalance = Tools.getDouble(appUser.getBalance());
            //新余额
            Double newBalance = 0.00D;
            if(balanceType.intValue() == -1){ //减量
                //减少
                newBalance = Math.sub(oldBalance, balance);
                changeBalance = Math.sub(0, balance);
            }else if(balanceType.intValue() == 1){ //增量
                //增加
                newBalance = Math.add(oldBalance, balance);
                changeBalance = balance;
            }else{//修改成指定值
                newBalance = balance;
                changeBalance = Math.sub(newBalance, oldBalance);
            }
            appUser.setBalance(newBalance);

            content.append("变动余额:" + changeBalance).append(";");
        }


        //表示修改积分
        Integer integral = updateBalanceDto.getIntegral();
        //变更积分
        Integer changeIntegral = 0;
        if(integral != null) {
            //修改积分类型
            Integer integralType = updateBalanceDto.getIntegralType();
            if(integralType == null){ //修改积分
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入积分修改类型");
            }
            if(!Lists.newArrayList(-1,0,1).contains(integralType)){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "积分修改类型值有误");
            }

            //旧积分
            Integer oldIntegral = Tools.getInteger(appUser.getIntegral());
            //新积分
            Integer newIntegral = 0;

            if(integralType.intValue() == -1){ //减量
                //减少
                newIntegral = oldIntegral - integral;
                changeIntegral = 0 - integral;
            }else if(integralType.intValue() == 1){ //增量
                //增加
                newIntegral = oldIntegral + integral;
                changeIntegral = integral;
            }else{//修改成指定值
                newIntegral = integral;
                changeIntegral = newIntegral - oldIntegral;
            }

            appUser.setIntegral(newIntegral);
            content.append("变动积分:" + changeIntegral).append(";");
        }

        Integer nowTime = DateUtil.getNowTime();
        appUser.setUpdateTime(nowTime);
        int j = appUserMapper.updateBalance(appUser);
        if (j != 1) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
        }

        //增加账号入账明细
        UserAccDetail appUserAccDetail = new UserAccDetail();
        appUserAccDetail.setId(IdWorker.getId());
        appUserAccDetail.setMerId(appUser.getMerId());
        appUserAccDetail.setUserId(appUser.getId());
        appUserAccDetail.setDeviceUniqueId(appUser.getDeviceUniqueId());
        appUserAccDetail.setDeviceType(appUser.getDeviceType());
        appUserAccDetail.setChangeInte(updateBalanceDto.getIntegral());
        appUserAccDetail.setChangeBal(updateBalanceDto.getBalance());
        appUserAccDetail.setNewBal(appUser.getBalance());
        appUserAccDetail.setNewInte(appUser.getIntegral());
        appUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
        appUserAccDetail.setRemark(updateBalanceDto.getRemark());
        appUserAccDetail.setCreateTime(nowTime);
        appUserAccDetail.setUpdateTime(nowTime);
        //插入用户账户明细记录
        int insert = userAccDetailMapper.insert(appUserAccDetail);
        if(insert!=1){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
        }

        AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
        alarmMsgFeignDto.setMerId(updateBalanceDto.getMerId());
        alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员余额和积分
        //消息
        JSONObject ext = new JSONObject();
        //当前操作员
        String token_key = String.format(CacheKey.LOGIN_TOKEN, updateBalanceDto.getLoginToken());
        Object data = redisTemplate.opsForValue().get(token_key);
        LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
        if(loginVo == null){
            loginVo = new LoginVo();
        }
        ext.put("childuser", loginVo.getLoginName());
        ext.put("content", content.toString());
        ext.put("nick", appUser.getNickName());
        ext.put("wxid", appUser.getBizUserId());
        ext.put("userid", appUser.getId());
        ext.put("phone", loginVo.getMobile());
        alarmMsgFeignDto.setExt(ext.toJSONString());
//        UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//        logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));
        //2024-01-09修改成直接发送MQ
        noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);
    }

    /**
     * 修改微信用户定向比例
     *
     * @param rewardRulesDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateWechatUserPriRewardRules(AppUserUpdatePriRewardRulesDto rewardRulesDto) {
        if (rewardRulesDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUser appUser = appUserMapper.selectById(rewardRulesDto.getId(), rewardRulesDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取设置定向规则JSON对象
        Map<String, AppPriRewardRulesDto> priRewardRules = JSONObject.parseObject(appUser.getPriRewardRules(), new TypeReference<Map<String, AppPriRewardRulesDto>>() {
        });
        if (priRewardRules == null) {
            priRewardRules = new HashMap<>();
        }

        //获取该运营商开启的产品模块
        MerBaseConfig merBaseConfig = merBaseConfigMapper.selectByMerId(rewardRulesDto.getMerId(), MerConfigKeyEnum.PRODUCT_SWITCH.getValue());
        if (merBaseConfig != null) {
            //获取该运营商开启的产品模块
            List<String> productKeyList = JSONObject.parseArray(merBaseConfig.getVal(), String.class);
            if (productKeyList != null && productKeyList.size() > 0) {
                //是否包含淘宝
                if (productKeyList.contains(ProductKeyEnum.TB.getValue())) {
                    AppPriRewardRulesDto tbRule = rewardRulesDto.getTbRule();
//                    if(tbRule != null){
//                        Long priRuleId = tbRule.getPriRuleId();
//                        if(priRuleId == null){
//                            tbRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("tbRule", tbRule);
                }

                //是否包含京东
                if (productKeyList.contains(ProductKeyEnum.JD.getValue())) {
                    AppPriRewardRulesDto jdRule = rewardRulesDto.getJdRule();
//                    if(jdRule != null){
//                        Long priRuleId = jdRule.getPriRuleId();
//                        if(priRuleId == null){
//                            jdRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("jdRule", jdRule);
                }

                //是否包含拼多多
                if (productKeyList.contains(ProductKeyEnum.PDD.getValue())) {
                    AppPriRewardRulesDto pddRule = rewardRulesDto.getPddRule();
//                    if(pddRule != null){
//                        Long priRuleId = pddRule.getPriRuleId();
//                        if(priRuleId == null){
//                            pddRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("pddRule", pddRule);
                }

                //是否包含唯品会
                if (productKeyList.contains(ProductKeyEnum.VPH.getValue())) {
                    AppPriRewardRulesDto vphRule = rewardRulesDto.getVphRule();
//                    if(vphRule != null){
//                        Long priRuleId = vphRule.getPriRuleId();
//                        if(priRuleId == null){
//                            vphRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("vphRule", vphRule);
                }

                //是否包含本地生活
                if (productKeyList.contains(ProductKeyEnum.LOCAL_LIVE.getValue())) {
                    AppPriRewardRulesDto localLiveRule = rewardRulesDto.getLocalLiveRule();
//                    if(localLiveRule != null){
//                        Long priRuleId = localLiveRule.getPriRuleId();
//                        if(priRuleId == null){
//                            localLiveRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("localLiveRule", localLiveRule);
                }

                //是否包含抖音
                if (productKeyList.contains(ProductKeyEnum.DY.getValue())) {
                    AppPriRewardRulesDto dyRule = rewardRulesDto.getDyRule();
//                    if(dyRule != null){
//                        Long priRuleId = dyRule.getPriRuleId();
//                        if(priRuleId == null){
//                            dyRule.setLadderId(null);
//                        }
//                    }
                    priRewardRules.put("dyRule", dyRule);
                }
            }
        }

        appUser.setPriRewardRules(Tools.getStrEmpty(JSONObject.toJSONString(priRewardRules)));
        appUser.setUpdateTime(DateUtil.getNowTime());

        appUserMapper.updateByIdSelective(appUser);


        //修改ES
        try {
            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.APP.getKey() + "_" + appUser.getMerId() + "_" + appUser.getBizUserId();
            //查询会员基本信息
            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, appUser.getMerId()), uzai_user_ext_info_id, null);
            if (dataMp_ext != null) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("priRewardRules", Tools.getStr(appUser.getPriRewardRules()));  //修改定向比例
                jsonObject.put("updateTime", DateUtil.getNowTime());

                elasticsearchUtil.updateDataById(jsonObject, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, appUser.getMerId()), uzai_user_ext_info_id);
            }

            //解决ES延时删除
            Thread.sleep(1000);

        } catch (Exception e) {
            logger.error("删除ES会员扩展信息出现异常:{}" + e.getMessage());
        }

    }

    /**
     * 加入黑名单
     *
     * @param appUserAddBlackDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void addBlackUser(AppUserAddBlackDto appUserAddBlackDto) {
        if (appUserAddBlackDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUser appUser = appUserMapper.selectById(appUserAddBlackDto.getId(), appUserAddBlackDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员不存在");
        }

        Integer now = DateUtil.getNowTime();

        //查询是否已经在黑名单当中
        //id为merId_wxid
        String id = appUser.getMerId() + "_" + appUser.getBizUserId();
        Map<String, Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id, null);
        WechatBlacklistPrv wechatBlacklistPrv = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WechatBlacklistPrv.class);
        if (wechatBlacklistPrv != null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员已经在黑名单中");
        }
        //添加到全网黑名单
        if (appUserAddBlackDto.getAllBackFlag() != null && appUserAddBlackDto.getAllBackFlag().intValue() == 1) {
            Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, appUser.getBizUserId(), null);
            WechatBlacklistPub wechatBlacklistPub = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
            if (wechatBlacklistPub != null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员已经在共享黑名单里");
            }
        }

        if (wechatBlacklistPrv == null) {
            wechatBlacklistPrv = new WechatBlacklistPrv();
            wechatBlacklistPrv.setId(id);
            wechatBlacklistPrv.setMerId(appUser.getMerId());
            wechatBlacklistPrv.setDeviceUniqueId(appUser.getDeviceUniqueId());
            wechatBlacklistPrv.setDeviceType(appUser.getDeviceType());
            wechatBlacklistPrv.setWxid(appUser.getBizUserId());
            wechatBlacklistPrv.setNickName(appUser.getNickName());
            wechatBlacklistPrv.setHeadImg(appUser.getHeadImg());
            wechatBlacklistPrv.setType(appUserAddBlackDto.getUserBlackType());
            wechatBlacklistPrv.setCreateTime(now);
            wechatBlacklistPrv.setRemark(appUserAddBlackDto.getRemark());
            wechatBlacklistPrv.setUpdateTime(now);
            elasticsearchUtil.addData(wechatBlacklistPrv, EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id);

            //添加到全网黑名单
            if (appUserAddBlackDto.getAllBackFlag() != null && appUserAddBlackDto.getAllBackFlag().intValue() == 1) {
                Map<String, Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, appUser.getBizUserId(), null);
                WechatBlacklistPub wechatBlacklistPub = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
                //全网黑名单中不存在
                if (wechatBlacklistPub == null) {
                    wechatBlacklistPub = new WechatBlacklistPub();
                    BeanUtils.copyProperties(wechatBlacklistPrv, wechatBlacklistPub);
                    wechatBlacklistPub.setId(appUser.getBizUserId());
                    wechatBlacklistPub.setCreateTime(now);
                    wechatBlacklistPub.setUpdateTime(now);
                    //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                    wechatBlacklistPub.setSource(0);
                    //增加到全网黑名单
                    elasticsearchUtil.addData(wechatBlacklistPub, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, appUser.getBizUserId());
                }
            }
        }

        try {
            //延迟0.5秒
            Thread.sleep(500);
        } catch (Exception e) {

        }
    }

    /**
     * 修改微信用户会员标签
     * @author liuqi
     * @date 2021/8/25 11:38
     * @param userUpdateMarketingTagDto
     * @return null
     */
    public void updateSysTags(UserUpdateMarketingTagDto userUpdateMarketingTagDto){
        if(userUpdateMarketingTagDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员id");
        }
        AppUser appUser = appUserMapper.selectById(userUpdateMarketingTagDto.getId(), userUpdateMarketingTagDto.getMerId());

        if(appUser == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该app会员不存在");
        }

        appUser.setSysTags(Tools.getStrEmpty(JSONObject.toJSONString(userUpdateMarketingTagDto.getSysTagList())));

        appUserMapper.updateSysTags(appUser);

    }


    /**
     * 修改微信用户详情信息
     *
     * @param updateDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateWechatUserInfo(AppUserInfoUpdateDto updateDto) {

        if (updateDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUser appUser = appUserMapper.selectById(updateDto.getId(), updateDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        //获取运营商ID
        Long merId = appUser.getMerId();
        //用户Id
        Long id = appUser.getId();

        //发送修改会员数据提醒通知
        StringBuffer content = new StringBuffer("正在修改会员信息;");

        //微信昵称
        if (!Tools.getStr(updateDto.getNickName()).equals(Tools.getStr(appUser.getNickName()))) {
            appUser.setNickName(Tools.getStr(updateDto.getNickName()));
        }

        //会员类型
        if (updateDto.getUserType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员类型不能为空");
        }
        UserType userType = userTypeMapper.selectById(updateDto.getUserType(), appUser.getMerId());
        if (userType == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员类型不存在或已删除");
        }

        //是否修改会员类型
        if (Tools.getLong(updateDto.getUserType()).longValue() != Tools.getLong(appUser.getUserType()).longValue()) {
            appUser.setUserType(updateDto.getUserType());
            content.append("新会员类型:" + userType.getName()).append(";");
        }

        //支付宝姓名
        Boolean updateAlipayInfoFlag = false;
        if (!Tools.getStr(updateDto.getAlipayName()).equals(Tools.getStr(appUser.getAlipayName()))) {
            appUser.setAlipayName(updateDto.getAlipayName());
            updateAlipayInfoFlag = true;
        }

        //支付宝账号
        if (!Tools.getStr(updateDto.getAlipayAccount()).equals(Tools.getStr(appUser.getAlipayAccount()))) {
            appUser.setAlipayAccount(updateDto.getAlipayAccount());
            updateAlipayInfoFlag = true;
        }

        //淘宝订单尾号
//        if(Tools.getInteger(updateDto.getTbLastOrderNo()).intValue() != Tools.getInteger(appUser.getTbLastOrderNo()).intValue()){
//            appUser.setTbLastOrderNo(Tools.getInteger(updateDto.getTbLastOrderNo()));
//        }

        //最后下单时间
        if(Tools.getInteger(updateDto.getLastOrderTime()).intValue() != Tools.getInteger(appUser.getLastOrderTime()).intValue()){
            appUser.setLastOrderTime(Tools.getInteger(updateDto.getLastOrderTime()));
        }

        //自定义标签
        List<String> addTagsList = updateDto.getTagsArr();
        String tagsStr = Tools.getStrEmpty(JSONObject.toJSONString(addTagsList));
        if (!tagsStr.equals(Tools.getStrEmpty(appUser.getTags()))) {
            appUser.setTags(Tools.getStrEmpty(JSONObject.toJSONString(addTagsList)));
        }

        //会员标签
        List<SysTagVo> sysTagsList = updateDto.getSysTagsList();
        String sysTagsStr = Tools.getStrEmpty(JSONObject.toJSONString(sysTagsList));
        if(!sysTagsStr.equals(Tools.getStrEmpty(appUser.getSysTags()))){
            appUser.setSysTags(sysTagsStr);
        }

        //是否修改备注
        Boolean setRemarkFlag = false;
        if (!Tools.getStr(updateDto.getRemark()).equals(Tools.getStr(appUser.getRemark()))) { //修改了备注
            //备注
            appUser.setRemark(updateDto.getRemark());
            setRemarkFlag = true;
        }

        //身份
        if (updateDto.getIdentity() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "身份不能为空");
        }

        if (userType.getIdentity().intValue() != updateDto.getIdentity().intValue()) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "选择的会员类型与会员身份不一样");
        }

        //是否修改身份证标志
        boolean flag_identity = false;
        //旧身份
        int identityOld = appUser.getIdentity().intValue();
        //新身份
        int identityNew = updateDto.getIdentity().intValue();

        //旧上级买家
        long parentIdOld = Tools.getLong(appUser.getParentId()).longValue();

        //旧代理
        long agentIdOld = Tools.getLong(appUser.getAgentId()).longValue();

        //旧合伙人
        long partnerIdOld = Tools.getLong(appUser.getPartnerId()).longValue();

        //旧身份自己买家树
        String parentInfoOld_wo = Tools.getStr(appUser.getParentInfo());

        //旧身份的所有下级的上级买家树
        String parentInfoOld_son = null;
        if (parentIdOld != 0) {
            parentInfoOld_son = Tools.getStrConnect(String.valueOf(appUser.getId()), "_", parentInfoOld_wo);
        } else {
            parentInfoOld_son = String.valueOf(appUser.getId());
        }

        //旧身份自己的代理树
        String agentInfoOld_wo = Tools.getStr(appUser.getAgentInfo());

        //旧身份的下级的代理树
        String agentInfoOld_son = null;
        if (agentIdOld != 0) {
            agentInfoOld_son = Tools.getStrConnect(String.valueOf(appUser.getId()), "_", agentInfoOld_wo);
        } else {
            agentInfoOld_son = String.valueOf(appUser.getId());
        }

        //如果新身份是合伙人:合伙人、代理、上级买家全部清空
        if (identityNew == IdentityEnum.PARTNER.getId()) {
            updateDto.setPartnerId(0L); //修改合伙人
            updateDto.setAgentId(0L); //修改代理
            updateDto.setParentId(0L); //修改上级买家
        } else if (identityNew == IdentityEnum.AGENT.getId()) { //如果新身份是代理:上级买家清空
            updateDto.setParentId(0L);
        }

        //判断是否修改了身份
        if (identityNew != identityOld) { //修改身份
            flag_identity = true;       //修改身份标志为true
            appUser.setIdentity(identityNew); //修改身份属性值
            content.append("新身份:" + IdentityEnum.getById(identityNew).getDesc()).append(";");
        }

        //新上级买家
        long parentIdNew = Tools.getLong(updateDto.getParentId()).longValue();

        //新代理
        long agentIdNew = Tools.getLong(updateDto.getAgentId()).longValue();

        //新合伙人
        long partnerIdNew = Tools.getLong(updateDto.getPartnerId()).longValue();

        //验证合伙人ID是否为合伙人
        boolean flag_partner = false;
        if (partnerIdNew != partnerIdOld) { //修改了合伙人

            //标志合伙人已经修改
            flag_partner = true;

            appUser.setPartnerId(partnerIdNew); //修改自己的合伙人信息

            //选择了合伙人，验证对方身份
            if (partnerIdNew != 0) {
                AppUser appUserPartner_new = appUserMapper.selectById(partnerIdNew, updateDto.getMerId());
                //判断存不存在
                if (appUserPartner_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不存在");
                }
                //判断身份
                if (appUserPartner_new.getIdentity() == null || appUserPartner_new.getIdentity().intValue() != IdentityEnum.PARTNER.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不是合伙人身份");
                }
                //判断是否为自己
                if (appUserPartner_new.getId().longValue() == appUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该合伙人不能是自己本身");
                }
                content.append("新合伙人:" + partnerIdNew).append(";");
            } else {
                content.append("清空合伙人").append(";");
            }
        }

        //验证上级会员ID是否为买家
        boolean flag_parent = false;
        String parentInfoNew_wo = parentInfoOld_wo;   //默认新的等于旧的，如果修改了，则变成新的
        String parentInfoNew_son = parentInfoOld_son; //默认新的等于旧的，如果修改了，则变成新的
        if (parentIdNew != parentIdOld) {//修改了上级买家
            //标志上级买家已经修改
            flag_parent = true;
            //修改上级买家ID
            appUser.setParentId(parentIdNew);

            //验收上级买家
            if (parentIdNew != 0) { //选择了上级买家
                AppUser appUserParent_new = appUserMapper.selectById(parentIdNew, updateDto.getMerId());
                //判断存不存在
                if (appUserParent_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不存在");
                }
                //判断身份
                if (appUserParent_new.getIdentity() == null || appUserParent_new.getIdentity().intValue() != IdentityEnum.BUYER.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不是买家身份");
                }
                //判断是否为自己
                if (appUserParent_new.getId().longValue() == appUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String parentInfo = Tools.getStr(appUserParent_new.getParentInfo());
                if (parentInfo.contains(String.valueOf(appUser.getId()))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级买家不能是自己的下级买家");
                }
                //判断新上级买家是否有上级买家，
                if (Tools.getLong(appUserParent_new.getParentId()).longValue() != 0) {//如果新上级买家有上级买家
                    parentInfoNew_wo = Tools.getStrConnect(String.valueOf(appUserParent_new.getId()), "_", appUserParent_new.getParentInfo());
                    appUser.setParentInfo(parentInfoNew_wo);
                } else {
                    parentInfoNew_wo = String.valueOf(appUserParent_new.getId());
                    appUser.setParentInfo(parentInfoNew_wo);
                }
                //所有下级的新的上级买家树
                parentInfoNew_son = Tools.getStrConnect(String.valueOf(appUser.getId()), "_", parentInfoNew_wo);

                content.append("新上级:" + parentIdNew).append(";");

            } else { //取消了上级买家
                //修改自己的上级树
                parentInfoNew_wo = "";
                appUser.setParentInfo(parentInfoNew_wo);
                //所有下级新的上级买家树
                parentInfoNew_son = String.valueOf(appUser.getId());

                content.append("清空上级").append(";");
            }
        }

        //验证代理身份是否为代理人
        boolean flag_agent = false;
        String agentInfoNew_wo = agentInfoOld_wo;    //默认新的等于旧的，如果修改了，则变成新的
        String agentInfoNew_son = agentInfoOld_son;  //默认新的等于旧的，如果修改了，则变成新的
        if (agentIdNew != agentIdOld) { //表示修改了上级代理
            //标志上级代理已经修改
            flag_agent = true;
            //修改代理属性
            appUser.setAgentId(agentIdNew);

            if (agentIdNew != 0) { //选择了上级代理，需要验证身份
                AppUser appUserAgent_new = appUserMapper.selectById(agentIdNew, updateDto.getMerId());
                //判断存不存在
                if (appUserAgent_new == null) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不存在");
                }
                //判断身份
                if (appUserAgent_new.getIdentity() == null || appUserAgent_new.getIdentity().intValue() != IdentityEnum.AGENT.getId()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该代理人不是代理人身份");
                }

                //判断是否为自己
                if (appUserAgent_new.getId().longValue() == appUser.getId().longValue()) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己本身");
                }

                //判断上级是否为自己的下级，如果是自己的下级，则上级树中包含自己的ID
                String agentInfo = Tools.getStr(appUserAgent_new.getAgentInfo());
                if (agentInfo.contains(String.valueOf(appUser.getId()))) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该上级代理不能是自己的下级代理");
                }

                //判断代理是否有上级代理
                if (Tools.getLong(appUserAgent_new.getAgentId()) != 0) { //代理有上级代理
                    agentInfoNew_wo = Tools.getStrConnect(String.valueOf(appUserAgent_new.getId()), "_", appUserAgent_new.getAgentInfo());
                    appUser.setAgentInfo(agentInfoNew_wo);
                } else {
                    agentInfoNew_wo = String.valueOf(appUserAgent_new.getId());
                    appUser.setAgentInfo(agentInfoNew_wo);
                }
                //所有下级的新的代理
                agentInfoNew_son = Tools.getStrConnect(String.valueOf(appUser.getId()), "_", agentInfoNew_wo);

                content.append("新代理:" + agentIdNew).append(";");

            } else { //取消了上级买家
                //修改自己的上级树
                agentInfoNew_wo = "";
                appUser.setAgentInfo(agentInfoNew_wo);
                //临时保存所有下级的新的代理树
                agentInfoNew_son = String.valueOf(appUser.getId());
                content.append("清空代理").append(";");
            }
        }

        //修改微信用户详情信息
        appUserMapper.updateById(appUser);

        //修改身份，改变了其他用户的树
        if (flag_identity) {
            //判断旧身份类型
            if (identityOld == IdentityEnum.BUYER.getId()) { // 旧身份是买家
                //判断新身份
                if (identityNew == IdentityEnum.AGENT.getId()) { //新身份是代理

                    /**买家转代理-身份往上升
                     * 1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件:A:买家树包含此ID，B:代理为空
                     * 2:修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无代理的用户代理设置为此Id，代理树也更新, 满足条件:A:买家树包含此ID，B:代理为空
                    appUserMapper.batchUpdateAgentInfoFromParentInfo(id, agentInfoNew_son, merId);
                    //2:修改下N级买家树（从此用户开始清空）
                    appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    appUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    AppUserQuery appUserQuery = new AppUserQuery();
                    appUserQuery.setMerId(merId);
                    appUserQuery.setParentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
                    //查询总数
                    Integer count = appUserMapper.findCount(appUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
                                if (appUserList != null && appUserList.size() > 0) {
                                    for (AppUser appUser_son : appUserList) {
                                        appUser_son.setParentId(0L);   //清空上级
                                        appUser_son.setParentInfo(""); //清空上级树
                                        appUser_son.setAgentId(id);    //修改代理
                                        appUser_son.setAgentInfo(agentInfoNew_son); //修改代理树
                                        appUserMapper.updateIdentityInfo(appUser_son);
                                        //4:将下N级代理和下N级代理的树更新
                                        String agentInfoOld_Nson = String.valueOf(appUser_son.getId());
                                        String agentInfoNew_Nson = appUser_son.getId() + "_" + appUser_son.getAgentInfo();
                                        //分俩次替换（避免替换留下"_"符合）
                                        appUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                        appUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.PARTNER.getId()) { //新身份是合伙人

                    /**买家转合伙人-身份往上升
                     * 1: 批量将下N级无合伙人的用户合伙人设置为此Id，满足条件:A:买家树包含此ID，B:合伙人为空
                     * 2:修改下N级买家树（从此用户开始清空）
                     * 3: 修改下级的上级和买家树（全部清空）
                     */
                    //1: 批量将下N级无合伙人的合伙人设置为此Id，满足条件:A:买家树包含此ID，B:合伙人为空
                    appUserMapper.batchUpdatePartnerInfoFromParentInfo(id, merId);
                    //2:修改下N级买家树（从此用户开始清空）
                    appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "", merId, true);
                    appUserMapper.batchUpdateParentInfo(parentInfoOld_son, "", merId, false);
                    //3: 修改下级的上级和买家树（全部清空）
                    AppUserQuery appUserQuery = new AppUserQuery();
                    appUserQuery.setMerId(merId);
                    appUserQuery.setParentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
                    //查询总数
                    Integer count = appUserMapper.findCount(appUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
                                if (appUserList != null && appUserList.size() > 0) {
                                    for (AppUser appUser_son : appUserList) {
                                        appUser_son.setParentId(0L);   //清空上级
                                        appUser_son.setParentInfo(""); //清空上级树
                                        appUser_son.setPartnerId(id);    //修改合伙人
                                        appUserMapper.updateIdentityInfo(appUser_son);
                                    }
                                }
                            }
                        }
                    }
                }
            } else if (identityOld == IdentityEnum.AGENT.getId()) { //旧身份是代理
                //判断新身份
                if (identityNew == IdentityEnum.BUYER.getId()) { //新身份是买家

                    /**代理转买家-身份往下降
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                     *  2:修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                    //appUserMapper.batchUpdateParentInfoFromAgentInfoAndParentIdNull(id, IdentityEnum.BUYER.getId(), parentInfoNew_son, merId, 0);

                    //2:修改下N级代理树
                    //分俩次替换（避免替换留下"_"符合）
                    appUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_wo, merId, true);
                    appUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_wo, merId, false);

                    //3: 修改下级的代理和代理树
                    AppUserQuery appUserQuery = new AppUserQuery();
                    appUserQuery.setMerId(merId);
                    appUserQuery.setAgentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
                    //查询总数
                    Integer count = appUserMapper.findCount(appUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
                                if (appUserList != null && appUserList.size() > 0) {
                                    for (AppUser appUser_son : appUserList) {
                                        appUser_son.setAgentId(agentIdNew);           // 修改新的上级代理
                                        appUser_son.setAgentInfo(agentInfoNew_wo);    //修改新的代理树

                                        //买家为空，且身份是买家
                                        if (appUser_son.getParentId().longValue() == 0L && appUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()) {
                                            appUser_son.setParentId(id);                  //修改上级
                                            appUser_son.setParentInfo(parentInfoNew_son); //修改上级树
                                            //将下N级上级和下N级的上级树更新
                                            String parentInfoOld_Nson = String.valueOf(appUser_son.getId());
                                            String parentInfoNew_Nson = appUser_son.getId() + "_" + appUser_son.getParentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            appUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        }

                                        appUserMapper.updateIdentityInfo(appUser_son);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.PARTNER.getId()) { //新身份是合伙人

                    /**代理转合伙人-身份往上升
                     *  1: 批量将下N级代理无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:代理树包含此ID，B:上级id为空；C:身份是买家
                     *  2:修改下N级代理树
                     *  3: 修改下级的代理和代理树
                     */

                    //1: 批量将下N级代理无合伙人的会员，将合伙人设置为此Id，满足条件:A:代理树包含此ID，B:合伙人为空；
                    appUserMapper.batchUpdatePartnerIdFromAgentInfo(id, merId);
                    //2:修改下N级代理树(清空截断）
                    //分俩次替换（避免替换留下"_"符合）
                    appUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "", merId, true);
                    appUserMapper.batchUpdateAgentInfo(agentInfoOld_son, "", merId, false);
                    //3: 修改下级的代理和代理树
                    AppUserQuery appUserQuery = new AppUserQuery();
                    appUserQuery.setMerId(merId);
                    appUserQuery.setAgentId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
                    //查询总数
                    Integer count = appUserMapper.findCount(appUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
                                if (appUserList != null && appUserList.size() > 0) {
                                    for (AppUser appUser_son : appUserList) {
                                        appUser_son.setAgentId(0L);                    // 清空代理人
                                        appUser_son.setAgentInfo("");                  //清空代理人信息
                                        appUser_son.setPartnerId(id);                  //修改合伙人
                                        appUserMapper.updateIdentityInfo(appUser_son);
                                    }
                                }
                            }
                        }
                    }
                }
            } else { //旧身份是合伙人
                //判断新身份
                if (identityNew == IdentityEnum.BUYER.getId()) { //新身份是买家

                    /**合伙人转买家-身份往下降
                     *  1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                     *  2:清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                    //appUserMapper.batchUpdateParentInfoFromPartnerIdAndParentIdNull(id, IdentityEnum.BUYER.getId(), parentInfoNew_son, merId, 0);
                    //2:清空下N合伙人信息,更新买家信息
                    AppUserQuery appUserQuery = new AppUserQuery();
                    appUserQuery.setMerId(merId);
                    appUserQuery.setPartnerId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
                    //查询总数
                    Integer count = appUserMapper.findCount(appUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
                                if (appUserList != null && appUserList.size() > 0) {
                                    for (AppUser appUser_son : appUserList) {
                                        appUser_son.setPartnerId(0L);                  // 清空合伙人
                                        //上级不能为空，代理不能为空，且身份是买家
                                        if (appUser_son.getParentId().longValue() == 0L && appUser_son.getAgentId().longValue() == 0L && appUser_son.getIdentity().intValue() == IdentityEnum.BUYER.getId().intValue()) {
                                            appUser_son.setParentId(id);                   //修改上级
                                            appUser_son.setParentInfo(parentInfoNew_son);  //修改上级树
                                            //将下N级上级和下N级的上级树更新
                                            String parentInfoOld_Nson = String.valueOf(appUser_son.getId());
                                            String parentInfoNew_Nson = appUser_son.getId() + "_" + appUser_son.getParentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_Nson, "_" + parentInfoNew_Nson, merId, true);
                                            appUserMapper.batchUpdateParentInfo(parentInfoOld_Nson, parentInfoNew_Nson, merId, false);
                                        }
                                        appUserMapper.updateIdentityInfo(appUser_son);
                                    }
                                }
                            }
                        }
                    }
                } else if (identityNew == IdentityEnum.AGENT.getId()) { //新身份是代理

                    /**合伙人转代理-身份往下降
                     *  1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                     *  2:清空下N合伙人信息,更新买家信息
                     */

                    //1: 批量将下N级合伙人无上级的买家，将上级设置为此Id，更新买家树，满足条件:A:合伙人id等于此ID，B:上级id为空；C:身份是买家
                    //appUserMapper.batchUpdateAgentInfoFromPartnerIdAndAgentIdNull(id, parentInfoNew_son, merId, 0);
                    //2:清空下N合伙人信息,更新买家信息
                    AppUserQuery appUserQuery = new AppUserQuery();
                    appUserQuery.setMerId(merId);
                    appUserQuery.setPartnerId(id);

                    //查询这个机器人的所有会员的最小和最大创建时间-根据创建时间10天内来分段查询
                    AppUserMinMaxCreateTimeVo minMaxCreateTimeVo = appUserMapper.findMinAndMaxCreateTime(appUserQuery);
                    //查询总数
                    Integer count = appUserMapper.findCount(appUserQuery);
                    //有总数，且最小创建时间有
                    if (minMaxCreateTimeVo != null && Tools.getInteger(count) != 0) {
                        //则循环查询5天内的创建的会员
                        int duration = 5 * 24 * 3600;
                        List<TimeVO> timeVOList = DateUtil.getTimeScope(minMaxCreateTimeVo.getMinCreateTime(), minMaxCreateTimeVo.getMaxCreateTime(), duration);
                        if (timeVOList != null && timeVOList.size() > 0) {
                            for (TimeVO timeVO : timeVOList) {
                                appUserQuery.setCreateTimeStart(timeVO.getBeginTime());
                                appUserQuery.setCreateTimeEnd(timeVO.getEndTime());
                                List<AppUser> appUserList = appUserMapper.findByList(appUserQuery);
                                if (appUserList != null && appUserList.size() > 0) {
                                    for (AppUser appUser_son : appUserList) {

                                        appUser_son.setPartnerId(0L);                  // 清空合伙人
                                        //上级不能为空，代理不能为空，且身份是代理
                                        if (appUser_son.getParentId().longValue() == 0L && appUser_son.getAgentId().longValue() == 0L && appUser_son.getIdentity().intValue() == IdentityEnum.AGENT.getId().intValue()) {
                                            appUser_son.setAgentId(id);                   //修改代理
                                            appUser_son.setAgentInfo(agentInfoNew_son);  //修改代理树

                                            //将下N级代理和下N级的代理树更新
                                            String agentInfoOld_Nson = String.valueOf(appUser_son.getId());
                                            String agentInfoNew_Nson = appUser_son.getId() + "_" + appUser_son.getAgentInfo();
                                            //分俩次替换（避免替换留下"_"符合）
                                            appUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_Nson, "_" + agentInfoNew_Nson, merId, true);
                                            appUserMapper.batchUpdateAgentInfo(agentInfoOld_Nson, agentInfoNew_Nson, merId, false);
                                        }

                                        appUserMapper.updateIdentityInfo(appUser_son);

                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        //如果修改了上级买家,批量修改下N级买家树
        if (flag_parent) {
            //分俩次替换（避免替换留下"_"符合）
            appUserMapper.batchUpdateParentInfo("_" + parentInfoOld_son, "_" + parentInfoNew_son, merId, true);
            appUserMapper.batchUpdateParentInfo(parentInfoOld_son, parentInfoNew_son, merId, false);
        }

        //如果修改了代理,批量修改下N级代理树
        if (flag_agent) {
            //分俩次替换（避免替换留下"_"符合）
            appUserMapper.batchUpdateAgentInfo("_" + agentInfoOld_son, "_" + agentInfoNew_son, merId, true);
            appUserMapper.batchUpdateAgentInfo(agentInfoOld_son, agentInfoNew_son, merId, false);
        }

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if (setRemarkFlag) {
            //查询机器人
            //发送MQ消息
            MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
            SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
            msgDto.setContent(setUserRemarkDto);
            msgDto.setId(IdWorker.getId());
            msgDto.setDeviceUniqueId(appUser.getDeviceUniqueId());
            msgDto.setDeviceType(DeviceTypeEnum.APP.getId());
            msgDto.setMerId(appUser.getMerId());
            msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
            setUserRemarkDto.setWxid(appUser.getBizUserId());
            setUserRemarkDto.setRemark(Tools.getStr(appUser.getRemark()));
            noticeMsgPushProducerService.setUserRemark(msgDto);

        }

        //是否修改了支付宝账号和姓名
        if (updateAlipayInfoFlag) {
            AlipayUserAuthDto alipayUserAuthDto = new AlipayUserAuthDto();
            alipayUserAuthDto.setAlipayUserId(appUser.getAlipayAccount());
            alipayUserAuthDto.setAlipayUserName(appUser.getAlipayName());
            alipayUserAuthDto.setUserId(String.valueOf(appUser.getId()));
            //获取该会员的appid配置1-获取默认机器人;2-获取机器人的配置方案；3-从配置方案的提现配置里获取appid
            if (appUser.getDeviceUniqueId() != null) {
                DeviceAppInfo deviceWechatInfo = deviceAppInfoMapper.selectById(appUser.getDeviceUniqueId(), appUser.getMerId());
                if (deviceWechatInfo != null && deviceWechatInfo.getConfigId() != null) {
                    ConfigPlan configPlan = configPlanMapper.selectById(deviceWechatInfo.getConfigId(), deviceWechatInfo.getMerId());
                    if (configPlan != null && configPlan.getUserTakeBalId() != null) {
                        SysPlugin sysPlugin = sysPluginMapper.selectById(configPlan.getUserTakeBalId(), configPlan.getMerId());
                        if (sysPlugin != null && StringUtils.isNotBlank(sysPlugin.getData())) {
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(sysPlugin.getData());
                                String zf_app_id = jsonObject.getString("zf_app_id");//账房appId
                                if (StringUtils.isNotBlank(zf_app_id)) {
                                    alipayUserAuthDto.setAppId(zf_app_id);
                                    UzaiRespVo<Object> objectUzaiRespVo = uzaiCashierServerFeignService.alipayUserAuth(alipayUserAuthDto);
                                    logger.info("--调用账房授权支付宝账号信息微服务接口--para={},result={}", JSONObject.toJSONString(alipayUserAuthDto), JSONObject.toJSONString(objectUzaiRespVo));
                                }
                            } catch (Exception e) {
                                logger.error("---配置方案的提现设置插件格式有问题---sysPluginId={}, configId={}, merId={}", sysPlugin.getId(), configPlan.getId(), configPlan.getMerId());
                            }
                        }
                    }
                }
            }
        }

        //发送异常报警通知-修改会员敏感信息
        if (StringUtils.isNotBlank(content)) {
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(updateDto.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER.getValue()); //修改会员敏感信息
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, updateDto.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            ext.put("childuser", loginVo.getLoginName());
            ext.put("content", content.toString());
            ext.put("nick", appUser.getNickName());
            ext.put("wxid", appUser.getBizUserId());
            ext.put("userid", appUser.getId());
            ext.put("phone", loginVo.getMobile());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送修改会员敏感信息报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));

            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }

        //修改ES缓存
        //修改ES
        try {

            //修改营销策略数据
            if(flag_parent || flag_agent || flag_partner){
                marketingRewardsService.updateMarketingRewards(appUser);
            }

            //修改会员扩展信息
            String uzai_user_ext_info_id = DeviceTypeEnum.APP.getKey() + "_" + appUser.getMerId() + "_" + appUser.getBizUserId();
            //查询会员基本信息
            Map<String, Object> dataMp_ext = elasticsearchUtil.searchDataById(merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, appUser.getMerId()), uzai_user_ext_info_id, null);
            if (dataMp_ext != null) {
                EsUserExtInfo esUserExtInfo = new EsUserExtInfo();
                BeanUtils.copyProperties(appUser, esUserExtInfo);
                esUserExtInfo.setId(uzai_user_ext_info_id);
                elasticsearchUtil.updateDataById(esUserExtInfo, merchantService.getMechantUserInfoEsName(EsIndexName.UZAI_USER_EXT_INFO, appUser.getMerId()), uzai_user_ext_info_id);
            }

            //解决ES延时删除
            Thread.sleep(1000);

        } catch (Exception e) {
            logger.error("修改会员营销策略信息出现异常:{}" + e.getMessage());
        }

    }

    /**
     * 用户发送消息
     *
     * @param sendMsgDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void sendMessageToOneUser(AppUserSendMsgDto sendMsgDto) {

        if (sendMsgDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID参数不能为空");
        }

        AppUser appUser = appUserMapper.selectById(sendMsgDto.getId(), sendMsgDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        if (StringUtils.isBlank(sendMsgDto.getMessage())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "发送消息为空 ");
        }

        Device device = deviceService.findDeviceInfoByDeviceUniqueId(appUser.getDeviceUniqueId(), appUser.getDeviceType(), sendMsgDto.getMerId());
        if (device == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户绑定的机器人id不存在");
        }

        //调用API服务发送消息
        // TODO: 2021/9/4  发送消息
        //发送MQ消息
        MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
        NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
        msgDto.setContent(noticeMsgDto);
        msgDto.setId(IdWorker.getId());
        msgDto.setDeviceType(device.getRecvmsgType());
        msgDto.setDeviceUniqueId(appUser.getDeviceUniqueId());
        msgDto.setMerId(appUser.getMerId());
        msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
        noticeMsgDto.setContent(sendMsgDto.getMessage());
        noticeMsgDto.setBizUserId(appUser.getBizUserId());
        noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
        noticeMsgDto.setGroupId(null);
        noticeMsgDto.setNickName(appUser.getNickName());
        noticeMsgDto.setMsgSource(1);
        noticeMsgDto.setDelay(0);
        noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
        noticeMsgPushProducerService.sendMessage(msgDto);

    }

    /**
     * 单个用户修改信息
     *
     * @param appUserUpdateDt
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateToOneUser(AppUserUpdateDto appUserUpdateDt) {

        //修改时间
        int nowTime = DateUtil.getNowTime();

        if (appUserUpdateDt.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户ID不存在");
        }

        AppUser appUser = appUserMapper.selectById(appUserUpdateDt.getId(), appUserUpdateDt.getMerId());
        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        //修改用户类型
        //查询新的用户类型
        if (appUserUpdateDt.getUserType() != null) {
            UserType userType_new = userTypeMapper.selectById(appUserUpdateDt.getUserType(), appUserUpdateDt.getMerId());
            //新会员类型不为空
            if (userType_new != null) {
                if (userType_new.getId().longValue() != appUser.getUserType().longValue()) {//修改了会员类型（修改了身份）
                    //需判断新会员类型是否跟旧会员类型在同一个组内，不同组内不能修改。否则会造成用户的会员类型组和绑定机器人配置方案里的会员类型组不一样
                    UserType userType_old = userTypeMapper.selectById(appUser.getUserType(), appUser.getMerId());
                    if (userType_old != null) {
                        if (userType_old.getGroupId().longValue() == userType_new.getGroupId().longValue()) { //如果不相等，表示不在同一个组内，则不让修改会员类型
                            AppUpdateIdentityDto updateIdentityDto = new AppUpdateIdentityDto();
                            updateIdentityDto.setMerId(appUserUpdateDt.getMerId());
                            updateIdentityDto.setId(appUser.getId());
                            updateIdentityDto.setUserTypeNew(appUserUpdateDt.getUserType());
                            updateIdentityDto.setIdentityNew(userType_new.getIdentity());
                            appUserTreeInfoService.updateIdentity(updateIdentityDto);
                        }
                    }
                }
            }
        }

        //修改定向规则
        //获取用户本身旧的定向规则JSON对象
        Map<String, AppPriRewardRulesDto> priRewardRulesMap_old = JSONObject.parseObject(appUser.getPriRewardRules(), new TypeReference<Map<String, AppPriRewardRulesDto>>() {
        });
        if (priRewardRulesMap_old == null) {
            priRewardRulesMap_old = new HashMap<>();
        }

        //获取页面设置的新的定向规则JSON对象
        Map<String, AppPriRewardRulesDto> priRewardRulesMap_new = JSONObject.parseObject(appUserUpdateDt.getPriRewardRules(), new TypeReference<Map<String, AppPriRewardRulesDto>>() {
        });
        if (priRewardRulesMap_new != null && priRewardRulesMap_new.size() > 0) {
            for (String key : priRewardRulesMap_new.keySet()) {
                //新定向规则
                AppPriRewardRulesDto priRewardRulesDto_new = priRewardRulesMap_new.get(key);
                //旧定向规则
                AppPriRewardRulesDto priRewardRulesDto_old = priRewardRulesMap_old.get(key);
                if (priRewardRulesDto_old == null) {
                    priRewardRulesDto_old = new AppPriRewardRulesDto();
                }
                //判断新的定向规则值
                if (priRewardRulesDto_new != null) {
                    //判断定向规则
                    if (priRewardRulesDto_new.getPriRuleId() != null) { //表示修改
                        if (priRewardRulesDto_new.getPriRuleId().longValue() < 0) { //表示清空
                            priRewardRulesDto_old.setPriRuleId(null);
                        } else {//表示修改
                            priRewardRulesDto_old.setPriRuleId(priRewardRulesDto_new.getPriRuleId());
                        }
                    }
                    //判断阶梯规则
                    if (priRewardRulesDto_new.getLadderId() != null) { //表示修改
                        if (priRewardRulesDto_new.getLadderId().longValue() < 0) { //表示清空
                            priRewardRulesDto_old.setLadderId(null);
                        } else {//表示修改
                            priRewardRulesDto_old.setLadderId(priRewardRulesDto_new.getLadderId());
                        }
                    }
                }
                //更新旧的定向规则
                priRewardRulesMap_old.put(key, priRewardRulesDto_old);
            }
        }
        //修改定向规则
        appUser.setPriRewardRules(Tools.getStrEmpty(JSONObject.toJSONString(priRewardRulesMap_old)));
        appUserMapper.updatePriRewardRules(appUser);

        //是否增加新标签列表
        List<String> userLabList = appUserUpdateDt.getUserLabList();
        //是否清空所有标签
        Integer cleanLab = appUserUpdateDt.getCleanLab();
        //清空指定标签列表
        List<String> cleanUserLabList = appUserUpdateDt.getCleanUserLabList();

        //开启清空所有标签
        if (cleanLab != null && cleanLab.intValue() == 1) {
            //添加新标签
            if (userLabList != null && userLabList.size() > 0) {
                appUser.setTags(JSONObject.toJSONString(userLabList));
            } else {
                appUser.setTags("");
            }
        } else { //未开启清空标签
            //旧标签
            String tags_old = appUser.getTags();
            List<String> tagsOldList = JSONObject.parseArray(tags_old, String.class);
            if (tagsOldList == null) {
                tagsOldList = new ArrayList<>();
            }

            //清空指定标签列表
            if (cleanUserLabList != null && cleanUserLabList.size() > 0) {
                tagsOldList.removeAll(cleanUserLabList);
            }

            //添加新标签
            if (userLabList != null && userLabList.size() > 0) {
                tagsOldList.addAll(userLabList);
            }

            //去重复
            tagsOldList = tagsOldList.stream().distinct().collect(Collectors.toList());
            appUser.setTags(JSONObject.toJSONString(tagsOldList));
        }

        //是否增加新会员标签列表
        List<SysTagVo> sysTagsList = appUserUpdateDt.getSysTagsList();
        //是否清空所有会员标签
        Integer cleanSysTags = appUserUpdateDt.getCleanSysTags();
        //清空指定会员标签列表
        List<SysTagVo> cleanSysTagsList = appUserUpdateDt.getCleanSysTagsList();

        //开启清空所有会员标签
        if(cleanSysTags != null && cleanSysTags.intValue() == 1){
            //添加新会员标签
            if(sysTagsList != null && sysTagsList.size() > 0){
                appUser.setSysTags(JSONObject.toJSONString(sysTagsList));
            }else{
                appUser.setSysTags("");
            }
        }else{//未开启清空会员标签
            //旧会员标签
            String sysTags_old = appUser.getSysTags();
            List<SysTagVo> sysTagsOldList = JSONObject.parseArray(sysTags_old, SysTagVo.class);
            if(sysTagsOldList == null){
                sysTagsOldList = new ArrayList<>();
            }

            //清空指定会员标签列表
            if(cleanSysTagsList != null && cleanSysTagsList.size() > 0){
                sysTagsOldList.removeAll(cleanSysTagsList);
            }

            //添加新会员标签
            if(sysTagsList != null && sysTagsList.size() > 0){
                if(sysTagsOldList.size() == 0){
                    sysTagsOldList.addAll(sysTagsList);
                }else{
                    //循环遍历，一个个增加,如果类型存在，则删除
                    for (SysTagVo sysTagVo : sysTagsList) {
                        for (int i = sysTagsOldList.size()-1; i>=0 ; i--) {
                            //如果标签类型相等，则删除旧标签
                            if(sysTagsOldList.get(i).getType().intValue() == sysTagVo.getType().intValue()){
                                sysTagsOldList.remove(i);
                            }else{
                                if(sysTagVo.getType().intValue() == MarketingTagTypeEnum.TAKETAL_NEED_EXAMINE_VALUE){
                                    if(sysTagsOldList.get(i).getType().intValue() == MarketingTagTypeEnum.TAKETAL_NOT_EXAMINE_VALUE){
                                        sysTagsOldList.remove(i);
                                    }
                                }else if(sysTagVo.getType().intValue() == MarketingTagTypeEnum.TAKETAL_NOT_EXAMINE_VALUE){
                                    if(sysTagsOldList.get(i).getType().intValue() == MarketingTagTypeEnum.TAKETAL_NEED_EXAMINE_VALUE){
                                        sysTagsOldList.remove(i);
                                    }
                                }
                            }
                        }
                    }
                    sysTagsOldList.addAll(sysTagsList);
                }
            }

            //去重复
            sysTagsOldList = sysTagsOldList.stream().distinct().collect(Collectors.toList());
            appUser.setSysTags(JSONObject.toJSONString(sysTagsOldList));
        }

        //是否修改备注
        Boolean setRemarkFlag = false;
        String userRemark = appUserUpdateDt.getUserRemark();
        if (StringUtils.isNotBlank(userRemark)) {
            //替换变量
            userRemark = userRemark.replaceFirst("\\[昵称\\]", appUser.getNickName());
            appUser.setRemark(Tools.getStr(userRemark));
            setRemarkFlag = true;
        }

        appUserMapper.updateRemarkAndTags(appUser);

        //是否修改了用户备注，如果修改了，则发送MQ同步手机微信好友，
        if (setRemarkFlag) {
            //查询机器人
            DeviceAppInfo deviceWechatInfo = deviceAppInfoMapper.selectById(appUser.getDeviceUniqueId(), appUser.getMerId());
            if (deviceWechatInfo != null) {
                //发送MQ消息
                MsgDto<SetUserRemarkDto> msgDto = new MsgDto<>();
                SetUserRemarkDto setUserRemarkDto = new SetUserRemarkDto();
                msgDto.setContent(setUserRemarkDto);
                msgDto.setId(IdWorker.getId());
                msgDto.setDeviceUniqueId(appUser.getDeviceUniqueId());
                msgDto.setDeviceType(DeviceTypeEnum.APP.getId());
                msgDto.setMerId(appUser.getMerId());
                msgDto.setMsgType(MessageFuncEnum.SET_USER_REMARK.getValue());
                setUserRemarkDto.setWxid(appUser.getBizUserId());
                setUserRemarkDto.setRemark(Tools.getStr(appUser.getRemark()));
                noticeMsgPushProducerService.setUserRemark(msgDto);
            }
        }


        //计算用户余额并修改
        //变更余额
        Double balance = appUserUpdateDt.getBalance();
        //变更积分
        Integer integral = appUserUpdateDt.getIntegral();
        //积分和余额只要有一个不等于null。表示有变更，则修改
        if(balance != null || integral != null){
            //发送修改会员数据提醒通知
            StringBuffer content = new StringBuffer("正在修改会员余额和积分;");
            appUser.setUpdateTime(nowTime);
            Double changeBalance = 0.0D;
            //表示修改余额
            if(balance != null){
                //修改类型类型
                Integer balanceType = appUserUpdateDt.getBalanceType();
                //旧余额
                Double oldBalance = Tools.getDouble(appUser.getBalance());
                //新余额
                Double newBalance = 0.00D;
                if(balanceType.intValue() == -1){ //减量
                    //减少
                    newBalance = Math.sub(oldBalance, balance);
                    changeBalance = Math.sub(0, balance);
                }else if(balanceType.intValue() == 1){ //增量
                    //增加
                    newBalance = Math.add(oldBalance, balance);
                    changeBalance = balance;
                }else{//修改成指定值
                    newBalance = balance;
                    changeBalance = Math.sub(newBalance, oldBalance);
                }
                appUser.setBalance(newBalance);
                content.append("变动余额:" + changeBalance).append(";");
            }

            //变更积分
            Integer changeIntegral = 0;
            if(integral != null) {
                //修改积分类型
                Integer integralType = appUserUpdateDt.getIntegralType();
                //旧积分
                Integer oldIntegral = Tools.getInteger(appUser.getIntegral());
                //新积分
                Integer newIntegral = 0;

                if(integralType.intValue() == -1){ //减量
                    //减少
                    newIntegral = oldIntegral - integral;
                    changeIntegral = 0 - integral;
                }else if(integralType.intValue() == 1){ //增量
                    //增加
                    newIntegral = oldIntegral + integral;
                    changeIntegral = integral;
                }else{//修改成指定值
                    newIntegral = integral;
                    changeIntegral = newIntegral - oldIntegral;
                }

                appUser.setIntegral(newIntegral);
                content.append("变动积分:" + changeIntegral).append(";");
            }
        
            int j = appUserMapper.updateBalance(appUser);
            if (j != 1) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.NET_ERROR);
            }
            //增加账号入账明细
            UserAccDetail appUserAccDetail = new UserAccDetail();
            appUserAccDetail.setId(IdWorker.getId());
            appUserAccDetail.setMerId(appUser.getMerId());
            appUserAccDetail.setUserId(appUser.getId());
            appUserAccDetail.setDeviceUniqueId(appUser.getDeviceUniqueId());
            appUserAccDetail.setDeviceType(appUser.getDeviceType());
            appUserAccDetail.setChangeInte(changeIntegral);
            appUserAccDetail.setChangeBal(changeBalance);
            appUserAccDetail.setNewBal(appUser.getBalance());
            appUserAccDetail.setNewInte(appUser.getIntegral());
            appUserAccDetail.setType(AccDetailTypeEnum.CHANGE_OPERATOR.getValue());
            appUserAccDetail.setRemark("运营商人为操作批量修改");
            appUserAccDetail.setCreateTime(nowTime);
            appUserAccDetail.setUpdateTime(nowTime);
            //插入用户账户明细记录
            int insert = userAccDetailMapper.insert(appUserAccDetail);
            if(insert!=1){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "增加账号明细失败");
            }

            //发送异常报警通知-修改会员敏感信息
            AlarmMsgFeignDto alarmMsgFeignDto = new AlarmMsgFeignDto();
            alarmMsgFeignDto.setMerId(appUser.getMerId());
            alarmMsgFeignDto.setType(SysMsgTypeEnum.OPE_UPDATE_USER_BAL_INTE.getValue()); //修改会员敏感信息
            //消息
            JSONObject ext = new JSONObject();
            //当前操作员
            String token_key = String.format(CacheKey.LOGIN_TOKEN, appUserUpdateDt.getLoginToken());
            Object data = redisTemplate.opsForValue().get(token_key);
            LoginVo loginVo = JSONObject.parseObject(String.valueOf(data), LoginVo.class);
            if(loginVo == null){
                loginVo = new LoginVo();
            }
            ext.put("childuser", loginVo.getLoginName());
            ext.put("content", content.toString());
            ext.put("nick", appUser.getNickName());
            ext.put("wxid", appUser.getBizUserId());
            ext.put("userid", appUser.getId());
            ext.put("phone", loginVo.getMobile());
            alarmMsgFeignDto.setExt(ext.toJSONString());
//            UzaiRespVo uzaiRespVo = uzaiBroadcastFeignService.sysMsgPush(alarmMsgFeignDto);
//            logger.info("---发送修改会员余额和积分报警消息-para={}, result={}", JSONObject.toJSONString(alarmMsgFeignDto), JSONObject.toJSONString(uzaiRespVo));
            //2024-01-09修改成直接发送MQ
            noticeMsgPushProducerService.sendSysAlarmMsgAsync(alarmMsgFeignDto);

        }

        //是否加入黑名单
        if (appUserUpdateDt.getUserBlackType() != null) {
            //查询是否已经在黑名单当中
            //id为merId_wxid
            String id = appUser.getMerId() + "_" + appUser.getBizUserId();
            Map<String, Object> map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id, null);
            WechatBlacklistPrv wechatBlacklistPrv = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(map)), WechatBlacklistPrv.class);
            //不存在，则表示还未加入黑名单，则加入
            if (wechatBlacklistPrv == null) {
                wechatBlacklistPrv = new WechatBlacklistPrv();
                wechatBlacklistPrv.setId(id);
                wechatBlacklistPrv.setMerId(appUser.getMerId());
                wechatBlacklistPrv.setDeviceUniqueId(appUser.getDeviceUniqueId());
                wechatBlacklistPrv.setDeviceType(appUser.getDeviceType());
                wechatBlacklistPrv.setWxid(appUser.getBizUserId());
                wechatBlacklistPrv.setNickName(appUser.getNickName());
                wechatBlacklistPrv.setHeadImg(appUser.getHeadImg());
                wechatBlacklistPrv.setType(appUserUpdateDt.getUserBlackType());
                wechatBlacklistPrv.setRemark(appUserUpdateDt.getUserBlackRemark());
                wechatBlacklistPrv.setCreateTime(nowTime);
                wechatBlacklistPrv.setUpdateTime(nowTime);
                elasticsearchUtil.addData(wechatBlacklistPrv, EsIndexName.UZAI_WECHAT_BLACKLIST_PRV, id);
            }

            //添加到全网黑名单
            if(appUserUpdateDt.getAllBackFlag() != null && appUserUpdateDt.getAllBackFlag().intValue() == 1){
                Map<String,Object> pub_map = elasticsearchUtil.searchDataById(EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, appUser.getBizUserId(), null);
                WechatBlacklistPub wechatBlacklistPub  = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(pub_map)), WechatBlacklistPub.class);
                //全网黑名单中不存在
                if(wechatBlacklistPub == null){
                    wechatBlacklistPub = new WechatBlacklistPub();
                    BeanUtils.copyProperties(wechatBlacklistPrv, wechatBlacklistPub);
                    wechatBlacklistPub.setId(appUser.getBizUserId());
                    wechatBlacklistPub.setCreateTime(nowTime);
                    wechatBlacklistPub.setUpdateTime(nowTime);
                    //数据来源(0运营商共享 1官方采集-免费  2收费名单)
                    wechatBlacklistPub.setSource(0);
                    //增加到全网黑名单
                    elasticsearchUtil.addData(wechatBlacklistPub, EsIndexName.UZAI_WECHAT_BLACKLIST_PUB, appUser.getBizUserId());
                }
            }

        }

        //是否加入提现黑名单
        if (Tools.getInteger(appUserUpdateDt.getTakeBalBlackFlag()).intValue() == 1) {//开启加入提现黑名单

            //判断会员id是否已经在黑名单当中
            TakeBalBlacklist takeBalBlacklist_old = takeBalBlacklistMapper.selectByUserId(appUserUpdateDt.getId(), appUserUpdateDt.getMerId());
            //不存在，则加入黑名单当中
            if (takeBalBlacklist_old == null) {
                TakeBalBlacklist takeBalBlacklist = new TakeBalBlacklist();
                takeBalBlacklist.setUserId(appUserUpdateDt.getId());
                takeBalBlacklist.setMerId(appUserUpdateDt.getMerId());
                takeBalBlacklist.setNickName(appUser.getNickName());
                takeBalBlacklist.setDeviceType(appUser.getDeviceType());
                takeBalBlacklist.setRemark(appUserUpdateDt.getTakeBalBlackRemark());
                takeBalBlacklist.setAlipayAccount(appUser.getAlipayAccount());
                takeBalBlacklist.setId(IdWorker.getId());
                takeBalBlacklist.setCreateTime(nowTime);
                takeBalBlacklist.setUpdateTime(nowTime);
                //保存加入提现黑名单
                takeBalBlacklistMapper.insert(takeBalBlacklist);
            }
        }

        // 添加营销黑名单
        try {
            marketingRewardsBlackListService.addOrRemoveByFlag(appUser.getMerId(), String.valueOf(appUser.getId()), appUserUpdateDt.getMarketingRewardsBlackListRemark(), appUserUpdateDt.getMarketingRewardsBlackListFlag(),
                    appUserUpdateDt.getSubNotPassFriend());
        }catch (Exception e){

        }
    }

    /**
     * 单个用户定投筛选
     *
     * @param appUserOptCpcDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void optCpcToOneUser(AppUserOptCpcDto appUserOptCpcDto) {

        if (appUserOptCpcDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户id不存在");
        }

        AppUser appUser = appUserMapper.selectById(appUserOptCpcDto.getId(), appUserOptCpcDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "用户不存在");
        }

        if (appUserOptCpcDto.getCpaId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择定投项目");
        }

        //操作定投筛选功能
        // TODO: 2022/2/24

    }


    /**
     * 更新微信信息
     *
     * @param userIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public AppUserInfoVo updateUserInfoFromWechat(AppUserIdDto userIdDto) {

        //返回页面对象
        AppUserInfoVo appUserInfoVo = new AppUserInfoVo();

        if (userIdDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }
        AppUser appUser = appUserMapper.selectById(userIdDto.getId(), userIdDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        if (appUser.getDeviceUniqueId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员未绑定机器人信息");
        }

        //从ES中获取个人微信信息
        DeviceAppInfo deviceAppInfo = deviceAppInfoMapper.selectById(appUser.getDeviceUniqueId(), userIdDto.getMerId());

        if (deviceAppInfo == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员绑定的机器人不存在或者已经删除");
        }

        if (StringUtils.isNotBlank(deviceAppInfo.getDeviceId())) {
            String esId = appUser.getMerId() + "_" + deviceAppInfo.getDeviceId() + "_" + appUser.getBizUserId();
            try {
                //通过查询运营商其他索引分片获取分片索引
                String uzai_wx_contacts = EsIndexName.UZAI_WX_CONTACTS;
                uzai_wx_contacts = merchantService.getMechantOtherEsIndexName(uzai_wx_contacts, userIdDto.getMerId());
                Map<String, Object> dataMap = elasticsearchUtilGroupMsg.searchDataById(uzai_wx_contacts, esId, null);
                WxContactsInfoVo wxContactsInfoVo = JSONObject.parseObject(Tools.getStrEmpty(JSONObject.toJSONString(dataMap)), WxContactsInfoVo.class);
                if (wxContactsInfoVo != null) {
                    //更新微信信息
                    appUser.setNickName(wxContactsInfoVo.getNick());
                    appUser.setHeadImg(wxContactsInfoVo.getHimg());
                    appUser.setRemark(wxContactsInfoVo.getRemark());
                    appUserMapper.updateById(appUser);
                }
            } catch (Exception e) {
                logger.error("从ES中查询通讯录:error:" + e.getMessage());
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "更新微信信息失败");
            }
        }

        BeanUtils.copyProperties(appUser, appUserInfoVo);
        return appUserInfoVo;
    }

    /**
     * 修改互通的公众号会员的公众号
     *
     * @param updateWxpubUserDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void updateInterflowWxpubUser(AppUpdateWxpubUserDto updateWxpubUserDto) {
        //个人微信用户id
        Long id = updateWxpubUserDto.getId();
        //对应新的公众号id
        Long wxpubDeviceUniqueId = updateWxpubUserDto.getWxpubDeviceUniqueId();


        if (id == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人微信id不能为空");
        }

        if (wxpubDeviceUniqueId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "新公众号id不能为空");
        }

        AppUser appUser = appUserMapper.selectById(id, updateWxpubUserDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        String uzaiUnionId = appUser.getUzaiUnionId();

        if (StringUtils.isBlank(uzaiUnionId)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户还未互通公众号");
        }

        WxpubUser wxpubUser = wxpubUserMapper.selectByUzaiUnionId(uzaiUnionId, appUser.getMerId());
        if (wxpubUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户还未互通公众号");
        }

        WxpubInfoEntity wxpubInfoEntity = wxpubInfoMapper.queryObject(wxpubDeviceUniqueId);
        if (wxpubInfoEntity == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该公众号不存在或已删除");
        }

        wxpubUser.setDeviceUniqueId(wxpubDeviceUniqueId);
        wxpubUserMapper.updateDevice(wxpubUser);

    }


    /**
     * 清除会员的互通信息
     *
     * @param cleanUserUnionIdDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    public void cleanUserUnionId(AppCleanUserUnionIdDto cleanUserUnionIdDto) {
        Long merId = cleanUserUnionIdDto.getMerId();
        //来源会员id
        Long sourceUserId = cleanUserUnionIdDto.getSourceUserId();
        //来源设备类型（private_wechat：个人微信； work_wechat：企业微信；  wx_pub：公众号）
        String sourceDeviceType = cleanUserUnionIdDto.getSourceDeviceType();
        //需要解除会员id
        Long cleanUserId = cleanUserUnionIdDto.getCleanUserId();
        //需要解除的设备类型（private_wechat：个人微信； work_wechat：企业微信；  wx_pub：公众号）
        String cleanDeviceType = cleanUserUnionIdDto.getCleanDeviceType();

        if (merId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "系统参数错误");
        }

        if (sourceUserId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入来源会员id");
        }
        if (StringUtils.isBlank(sourceDeviceType)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入来源设备类型");
        }
        if (cleanUserId == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入需要解除的会员id");
        }
        if (StringUtils.isBlank(cleanDeviceType)) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入需要解除的设备类型");
        }

        //判断需要清除的设备类型为公众号，则需要清理来源会员的unionId
        if (DeviceTypeEnum.WX_PUB.getKey().equals(cleanDeviceType)) {
            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(sourceDeviceType)) { //来源是个人微信
                WechatUser wechatUser = wechatUserMapper.selectById(sourceUserId, merId);
                if (wechatUser != null) {
                    wechatUser.setUzaiUnionId(String.valueOf(wechatUser.getId()));
                    wechatUserMapper.updateUzaiUnionId(wechatUser);
                }
            } else if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(sourceDeviceType)) { //来源是企业微信
                WxworkUser wxworkUser = wxworkUserMapper.selectById(sourceUserId, merId);
                if (wxworkUser != null) {
                    wxworkUser.setUzaiUnionId(String.valueOf(wxworkUser.getId()));
                    wxworkUserMapper.updateUzaiUnionId(wxworkUser);
                }
            }
        } else {//不是清空公众号互通信息，则直接清除该会员的互通信息
            if (DeviceTypeEnum.DT_PC_WECHAT.getKey().equals(cleanDeviceType)) { //清除个人微信
                WechatUser wechatUser = wechatUserMapper.selectById(cleanUserId, merId);
                if (wechatUser != null) {
                    wechatUser.setUzaiUnionId(String.valueOf(wechatUser.getId()));
                    wechatUserMapper.updateUzaiUnionId(wechatUser);
                }
            } else if (DeviceTypeEnum.DT_WORK_WECHAT.getKey().equals(cleanDeviceType)) { //清除企业微信
                WxworkUser wxworkUser = wxworkUserMapper.selectById(cleanUserId, merId);
                if (wxworkUser != null) {
                    wxworkUser.setUzaiUnionId(String.valueOf(wxworkUser.getId()));
                    wxworkUserMapper.updateUzaiUnionId(wxworkUser);
                }
            }
        }
    }

    /**
     * 修改会员订阅信息
     *
     * @param updateSubscribeInfoDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateSubscribeInfo(AppUpdateSubscribeInfoDto updateSubscribeInfoDto) {
        //个人微信用户id
        Long id = updateSubscribeInfoDto.getId();

        AppUser appUser = appUserMapper.selectById(id, updateSubscribeInfoDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        appUser.setSubscribeInfo(updateSubscribeInfoDto.getSubscribeInfo());

        //修改会员订阅信息
        appUserMapper.updateSubscribeInfo(appUser);

    }

    /**
     * 修改会员营销奖励信息
     *
     * @param updateMarketingRewardDto
     * @return null
     * @author liuqi
     * @date 2021/8/25 11:38
     */
    @Transactional
    public void updateMarketingReward(AppUpdateMarketingRewardDto updateMarketingRewardDto) {
        //个人微信用户id
        Long userId = updateMarketingRewardDto.getId();

        AppUser appUser = appUserMapper.selectById(userId, updateMarketingRewardDto.getMerId());

        if (appUser == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该用户不存在");
        }

        MarketingRewardVo marketingReward = updateMarketingRewardDto.getMarketingReward();

        if (marketingReward == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入营销奖励信息");
        }

        String tradeno_old = StringUtils.join(userId, appUser.getRegSource());
        int now = DateUtil.getNowTime();

        //添加好友奖励
        if (marketingReward.getAddRe() != null) {
            MarketingRewardVo.ReDetail addRe = marketingReward.getAddRe();
            //奖励状态 0未奖励，1已奖励,
            if (addRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (addRe.getReBal() > 0 || addRe.getReInte() > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_REGIST.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REGISTER_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, appUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定上级，奖励下级
        if (marketingReward.getBindRe() != null) {
            MarketingRewardVo.ReDetail bindRe = marketingReward.getBindRe();
            //奖励状态 0未奖励，1已奖励,
            if (bindRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (bindRe.getReBal() > 0 || bindRe.getReInte() > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_INVITE.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, appUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定上级，奖励上级
        if (marketingReward.getBindReParent() != null) {
            MarketingRewardVo.ReDetail bindReParent = marketingReward.getBindReParent();
            //奖励状态 0未奖励，1已奖励,
            if (bindReParent.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (bindReParent.getReBal() > 0 || bindReParent.getReInte() > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_INVITE_PARENT.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_PARENT.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, appUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定代理，奖励代理
        if (marketingReward.getBindReAgent() != null) {
            MarketingRewardVo.ReDetail bindReAgent = marketingReward.getBindReAgent();
            //奖励状态 0未奖励，1已奖励,
            if (bindReAgent.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (bindReAgent.getReBal() > 0 || bindReAgent.getReInte() > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_ORDER_AGENT.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_AGENT.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, appUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //绑定合伙人，奖励合伙人
        if (marketingReward.getBindRePartner() != null) {
            MarketingRewardVo.ReDetail bindRePartner = marketingReward.getBindRePartner();
            //奖励状态 0未奖励，1已奖励,
            if (bindRePartner.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (bindRePartner.getReBal() > 0 || bindRePartner.getReInte() > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_ORDER_PARTNER.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.REWARD_INVITE_PARTNER.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, appUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首查奖励
        if (marketingReward.getFirstQueryRe() != null) {
            MarketingRewardVo.ReDetail firstQueryRe = marketingReward.getFirstQueryRe();
            //奖励状态 0未奖励，1已奖励,
            if (firstQueryRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (firstQueryRe.getReBal() > 0 || firstQueryRe.getReInte() > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_QUERY.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_QUERY_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, appUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首单奖励
        if (marketingReward.getFirstOrderRe() != null) {
            MarketingRewardVo.ReDetail firstOrderRe = marketingReward.getFirstOrderRe();
            //奖励状态 0未奖励，1已奖励,
            if (firstOrderRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (firstOrderRe.getReBal() > 0 || firstOrderRe.getReInte() > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_ORDER.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_ORDER_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, appUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //首次收货奖励
        if (marketingReward.getFirstSettledRe() != null) {
            MarketingRewardVo.ReDetail firstSettledRe = marketingReward.getFirstSettledRe();
            //奖励状态 0未奖励，1已奖励,
            if (firstSettledRe.getStatus() == 0) { //如果是未奖励，则需要判断奖励金额和奖励余额必须有一个不为0
                if (firstSettledRe.getReBal() > 0 || firstSettledRe.getReInte() > 0) {//再次给会员奖励，则需要将已经奖励的记录修改唯一索引
                    //账户明细
                    UserAccDetail userAccDetail = userAccDetailMapper.selectByUserIdAndTypeAndTradeno(userId, AccDetailTypeEnum.REWARD_FIRST_SETTLE.getValue(), tradeno_old);
                    if (userAccDetail != null) { //查询到已经奖励了，则修改transno
                        String tradeno_new = tradeno_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        userAccDetail.setTradeno(tradeno_new);
                        userAccDetail.setUpdateTime(now);
                        int i = userAccDetailMapper.updateByUserIdAndTypeAndTradeno(userAccDetail);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }

                    //红包明细
                    String tradeno_addRe_old = StringUtils.join(tradeno_old, RedPackTypeEnum.FIRST_SETTLED_GIVE.getValue());
                    RedPacket redPacket = redPacketMapper.selectByUserIdAndTradeno(userId, tradeno_addRe_old, appUser.getMerId());
                    if (redPacket != null) { //查询到已经奖励了，则修改transno
                        String tradeno_addRe_new = tradeno_addRe_old + "_" + Tools.getCurrentTimeByFormat("yyyyMMddHHmmss");
                        redPacket.setTradeno(tradeno_addRe_new);
                        redPacket.setUpdateTime(now);
                        int i = redPacketMapper.updateByUserIdAndTradeno(redPacket);
                        if (i != 1) {
                            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "修改失败，网络异常！");
                        }
                    }
                }
            }
        }

        //修改营销数据ES
        String uzai_marketing_reward_info = EsIndexName.UZAI_MARKETING_REWARD_INFO;
        elasticsearchUtil.addDataForObjectSerializer(marketingReward, uzai_marketing_reward_info, tradeno_old);

    }

}
